yup number validation code example

Example 1: yup phone validation

const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/

phoneNumber: Yup.string().matches(phoneRegExp, 'Phone number is not valid')

Example 2: yup only characters regex validation react

yup.string()
   .required("Please enter the required field")
   .matches(/^[aA-zZ\s]+$/, "Only alphabets are allowed for this field ")

Example 3: yup number validation custom message

numberFiled: Yup.number()
                        .typeError('you must specify a number')
                        .min(0, 'Min value 0.')
                        .max(30, 'Max value 30.')

Example 4: yup oneOf

// mixed.oneOf(arrayOfValues: Array<any>, message?: string | function): Schema Alias: equals
// Whitelist a set of values. Values added are automatically removed from any blacklist if they are in it. The ${values} interpolation can be used in the message argument.

// Note that undefined does not fail this validator, even when undefined is not included in arrayOfValues. If you don't want undefined to be a valid value, you can use mixed.required.

let schema = yup.mixed().oneOf(['jimmy', 42]);

await schema.isValid(42); // => true
await schema.isValid('jimmy'); // => true
await schema.isValid(new Date()); // => false