Home > database >  Simple validation of string/number behaving incorrectly
Simple validation of string/number behaving incorrectly

Time:11-08

I am using yup to perform a simple JavaScript data validation. However I am getting unexpected behaviour. I'm sure I'm misusing their API but this is not obvious to me after reviewing their docs. I run the following unit test and it fails (I expect it to pass). Any ideas?

import { object, string } from 'yup';

test('validator', async () => {
  let schema = object({
    name: string(),
  });

  expect(await schema.isValid({ name: 123 })).toEqual(false);
});

Using version

"yup": "^0.32.11"

Attempted running this validation and within a jest unit test and it fails. Tried reviewing their API docs for other validation methods

CodePudding user response:

This is the expected output because this is how the yup library has been implemented. When you apply the strict option to a schema the yup parser will not be run so erasing the possibility of transforming your number value to a string value due to the type_coercion. So with the strict option the number value 123 will be validated "as is" (no type_coercion), and because it is not a string value the validation will fail, without the strict option there will be the type coercion and the validation will be a success.

  • Related