Reputation: 3792
I'm using yup for validating my react form.
My problem is :
I have the below schema for validating an input field.
object().shape({
firstname: string()
.required('First Name is required')
.test('length', 'First Name must have more than 1 character', (value) => {
console.log(value && value.length < 2 ? true : false);
return value && value.length < 2 ? true : false;
})
.test('alphabets', 'Name must only contain alphabets', (value) => {
console.log(!/^[A-Za-z]+$/.test(value));
return !/^[A-Za-z]+$/.test(value);
})
});
When I enter a single character it shows Name must only contain alphabets
error message and when I try to type more characters it shows First Name must have more than 1 character
error message.
What should I do wrong?
Anyone, please help me with this?
Upvotes: 0
Views: 3955
Reputation: 5473
You seem to be doing both of your validation wrong way, you want to return true
if validation passes and false
if validation fails.
In your first validation value && value.length < 2 ? true : false
you are looking for value.length > 2
instead of <
and also no need to have ternary as comparison operator will return true/false value after evaluation.
In your second validation !/^[A-Za-z]+$/.test(value);
you are negating the validation by using !
Here's the corrected validation code:
object().shape({
firstname: string()
.required('First Name is required')
.test('length', 'First Name must have more than 1 character', (value) => {
return value && value.length > 2;
})
.test('alphabets', 'Name must only contain alphabets', (value) => {
return /^[A-Za-z]+$/.test(value);
})
});
Upvotes: 3