Reputation: 1620
I'm using yup with formik for validations. I want to validate a non-required field with yup. Here test is a non-required field but when user enters we are blocking him to enter some special characters. when the user didn't enter anything then also it is validating( i don't need this validation until user enters something). Can anyone help me, Thanks in advance
const validationSchema = function (values) {
return Yup.object().shape({
test: Yup.string()
.matches(/^[^<&>`#]+$/,'test should not contain `, &, #, <, > \n')
})
}
Upvotes: 0
Views: 2484
Reputation: 7821
The combination of errors.yourFieldName
and touched.yourFieldName
solves your problem:
So if the name of your input field is test
to show/hide errors :
{errors.test && touched.test ? {errors.test}: 'Valid form'}
and to enable/disable your submit button:
<button disabled={touched.test && (!isValid || isSubmitting)}>
I created a simple demo to illustrate this here https://codesandbox.io/s/q8vz32mpw
Upvotes: 2