Home > other >  Yup string length test validation with <= and not ===
Yup string length test validation with <= and not ===

Time:01-05

I'm trying to check to see if a string is less than or equal to 30 characters with Yup and react-hook-form in TypeScript.

I've found this example on SO to check if a string length === 5 and it works great, with just the type of error handling messaging I'm looking for.

The cited example validation works as expected when applied in my schema

title: Yup.string().test('len', 'Title must be exactly 5 characters', val => val?.length === 5).required('Title is required')

But with a change for my case (checking to see if the string is less than or equal to 30) I get an Object is possibly undefined error, even though I believe th ? should be covering the undefined case

title: Yup.string().test('len', 'Title must be less than or equal to 30 characters', val => val?.length <= 30).required('Title is required')

What's different between the use of === and <= in this case?

Thanks

CodePudding user response:

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.

  •  Tags:  
  • Related