jquense / yup

Dead simple Object schema validation
MIT License
22.93k stars 934 forks source link

Difficulties in choosing yup.number() and yup.string() #2232

Closed anujit closed 4 months ago

anujit commented 4 months ago

I'm using Yup for representing and validating values of a form. Two of the fields I have are - start and end which are numbers representing the start and end of a range of 11 digit numbers and thus are dependent on each other. So, for example, if the field start has value 20033322333, the field end can have any value which is greater than 20033322333, say for example, 50000000000. Any value lesser than the start value will be an invalid value for the end field and any value greater than the one in end will be invalid for start

Now I'm facing unique problems -

  1. Ideally I want these two fields to be represented as numbers (yup.number()) in the Yup Schema. I'm also doing a regex check on these values to make sure they contain exactly 11 digits. But the problem arises if any of the numbers start with a 0. Because of this the string value available in the test function of yup.number().test() is stripped off of any leading zeroes and so the regex validation fails if the numbers start with 0. For example String(01234567899) will be '1234567899' which will fail the regex for 11 digits.

  2. The other option is to use the yup.string() schema. But then I cannot use the moreThan and lessThan functions available on yup.number() which I need for validations inside yup.number().when() since the two fields are dependent on each other.

Could someone please advise what is the correct way to solve this problem I am facing or if there's anything that I am missing? Thanks.

anujit commented 4 months ago

closing this issue. i solved the problem at hand by having more control on the validation stage instead of focussing on the schema definition stage. this was done by writing custom validation logic by explicitly calling schema.validate in our code, instead of relying just on the integration of our form library (react-hook-form) with yup.