How do I create a validator that meets all of the following non-exclusive requirements and displays a different error message for each? I have a Formik form field for phone number. The validation requirement is
- No alphabetic characters (ASCII alphabets: [A-Za-Z])
- No period symbol
- No symbols, (non-period - e.g. ±, $, %, ^, etc.)
- Only digits, whitespace, and
(,),-
That requirement is easily handled with the catch-all regex: /^[\s\d\)\(\-]+$/ using:
phoneNo: yup
.string()
.min(6, 'Phone must be at least 6 characters')
.max(35, 'Phone number must be at most 35 characters')
.matches(/^[\s\d\)\(\-]+$/, { //original matcher
message: 'Invalid format.',
})
.matches(/\./, { //my test matcher
message: 'No period',
}),
However, the business wants individual error messages for each validator. So, for 1) no letters, 2) no period, 3) no symbols, and 4) only numbers and (,),-. At first I tried chaining multiple .matches() as above. If I input 111222., the message from the first matcher, invalid format would display. However, I expected No period. Since . is non-exclusive to both matchers, . fails the first check.
I tried both yup.test() and yup.addMethod but having no experience with yup beyond this, I could not get the syntax right in my head. I've spent hours researching this issue, so it's not for a lack of trying.
P.S. There is no request for validating the actual phone number schema, like (xxx)xxx-xxxx, just the values themselves. So a complete phone number regex is not necessary.
UPDATE: I've been trying to modify this solution to use this.matches(), but I don't understand how to pass in the value to be matched.
As an additional test, I tried using addMethod()
yup.addMethod(yup.string, 'noPeriod', function(errorMessage){
const regexPeriod = /\./;
return this.matches(regexPeriod, errorMessage);
});
However, when adding this function to the .shape() method
.shape({
phoneNo: yup.string()
.noPeriod('Period not allowed')
})
The TS linter rejects it with Property 'noPeriod' does not exist on type 'StringSchema<string, AnyObject, string>'.