I want to validate a not required form field with Yup
JavaScript
x
5
1
const validationSchema = Yup.object().shape({
2
firstname: Yup.string().required("First name is required").matches(/[A-Za-z]/,"Should contain only alphabets").min(3,'Should contain atleast ${min} alphabets`).max(20,`Should not exceed ${max} alphabets'),
3
lastname: Yup.string().nullable().notRequired()
4
})
5
lastname: Yup.string.nullable().notRequired()
. I don’t how to proceed further because I have multiple condition to validate the field if the input was given.
My validation condition are:
- Should contain only alphabets.
- Should be atleast minimum 2 and maximum 20 alphabets.
Advertisement
Answer
You should use similar match
pattern you already have for firstname
. One possible way of doing is like this:
JavaScript
1
17
17
1
const obj = {
2
firstname: 'my name',
3
lastname: 'asd'
4
};
5
const yupObj = yup.object().shape({
6
firstname: yup.string().required("First name is required").matches(/[A-Za-z]/,"Should contain only alphabets").min(3,'Should contain atleast 3 alphabets').max(20,`Should not exceed 20 alphabets`),
7
lastname: yup.string().nullable().notRequired().matches(/[a-zA-Z]{2,20}/, 'should have alphabets between 2 and 20')
8
})
9
yupObj
10
.validate(obj)
11
.then(function(value) {
12
console.log(value);
13
})
14
.catch(function(err) {
15
console.log(err);
16
});
17