Is it possible to use a Mask input plugin ( like react-text-mask ) with Formik?
Yup, you just treat it like any other custom input.
@jaredpalmer thanks. I've figured it out here. If anyone wanna see how I did it ( using react-text-mask
):
input = <Field name={name} render={({ field }) => {
return <MaskedInput mask={Masks[mappedField.mask]}
{...field}
id={name}
placeholder={mappedField.placeholder[language]} />
}} />
@ThiagoMiranda how did you managed to validate masked string?
For example with this yup:
passport: yup
.string()
.matches(/(^[0-9]+$)/, 'only digits here')
.required('enter something')
.min(4, 'Number of digits left: ' + digitsLeft)
.max(4, 'This is too much')
i get value "0___" and cant validate for min max rules.
How come this doesnt work
I see the masked input and its masking and rendering good, but when im typing values.masked is not updating, even though i have a name on the Field.
Because Field
passes a field
prop, which MaskedInput
doesn't correctly map to handlers.
Okey so field prop is not including all unknown props from Field
@yyynnn - I've hit the same issue. I ended up creating a custom change handler that strips the mask characters and manual calls Formik's setFieldValue
.
handleChange = (event, field, form, charsToStrip) => {
const cleanValue = stripCharacters(event.target.value, charsToStrip)
form.setFieldValue(field.name, cleanValue)
}
function stripCharacters (string, characters) {
const re = new RegExp(`[${characters}]+`, 'g')
return string.replace(re, '')
}
@ThiagoMiranda how did you managed to validate masked string?
...
i get value "0___" and cant validate for min max rules.
pls see for another example https://codesandbox.io/s/4rkyylp24w
@jaredpalmer thanks. I've figured it out here. If anyone wanna see how I did it ( using
react-text-mask
):this work for me too
<Field name='telefone' > {({ field }) => ( <MaskedInput mask={['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]} {...field} placeholder='Telefone' className="form-control" /> )} </Field>
Most helpful comment
@jaredpalmer thanks. I've figured it out here. If anyone wanna see how I did it ( using
react-text-mask
):