Validation Using Yup to Check String or Number Length

Validation using Yup to check string or number length

I don't think there's anything built in but it's easy to implement with test:

yup.string()
.test('len', 'Must be exactly 5 characters', val => val.length === 5)

https://runkit.com/tamlyn/5ad9b99a4ba1230012d7ac21

Validation using Yup to check number length

Try to add nullable() to your yup schema and a regular expression for the numbers, try something like this:

const regExp = /\b\d{5}\b/;

Yup.string().matches(regExp, {message: 'Must be exactly 5 numbers', excludeEmptyString: true})

Yup string length test validation with <= and not ===

When val is undefined, the optional chain will automatically convert val?.length to undefined as well.

The equality operator === is meant to work will all types of values, including undefined, so even if you run undefined === 15, it will still be valid in TypeScript.

However, the greater than and less than operators such as <= are only meant to be used with numbers. If you try to do undefined > 3, TypeScript will give you an Object is possibly undefined error.

Optional field validation in Yup schema

You need to use .when for conditional validation like this below. I have added only for address and city only, you can add for other like this.

export const updateAddressSchema = yup.object().shape({

address: yup.string().when("address", (val, schema) => {
if (val) {
if(val.length > 0) { //if address exist then apply min max else not
return yup.string().min(5, "min 5").max(255, "max 255").required("Required");
} else {
return yup.string().notRequired();
}

} else {
return yup.string().notRequired();
}
}),

city: yup.string().when("city", (val, schema) => {
if (val) {
if(val.length > 0) {
return yup.string().max(32, "max 32").required("Required");
}
else {
return yup.string().notRequired();
}
} else {
return yup.string().notRequired();
}
}),

}, [
["address", "address"],
["city", "city"],
] //cyclic dependency
);

Also, you need to add Cyclic dependency

How to strip an array if array length is 0 in yup

For someone who may encounter the same issue:

I found the issue in:

.when(".length", {
is: 0,
then: (s) => s.strip(),

I needed to reference the .length of the array rather than the arr.length and this resolved the problem.



Related Topics



Leave a reply



Submit