Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yup.js Validate number field is larger than sibling, or nullable

I'm using Yup.js to validate some form fields.

I have two integer fields, Year Built & Year Renovated.

Year Built is a required field, Year Renovated is not.

Year renovated can be left blank, however if there is a value it should be larger than year built (for a renovation certainly must occur after the date it was built).

I believe I need to use yup's ref() as well as yup's when() function. I've tried the following:

let currentYear = new Date().getFullYear();

yup.object().shape({
  yearBuilt     : yup.number().integer().min(1700).max(currentYear+1).required(),
  yearRenovated : yup.number().integer().when(
                    '$yearRenovated', (yearRenovated, schema)=>{
                        return yearRenovated > 0 ? 
                            schema.min(yup.ref('yearBuilt')).max(currentYear+1) :
                            schema.transform(emptyStringToNull).nullable()
                    }
                )
})

* The transform function, emptyStringToNull simply checks if value === '' and returns null if so.

The above does allow null values, as well as does correctly check for an integer. However it does not properly evaluate yearRenovated > yearBuilt. How do I properly check that if yearRenovated is not null, that it is greater than yearBuilt?

Thank you all so much for your help.

like image 716
ZAR Avatar asked May 07 '20 15:05

ZAR


People also ask

How do you validate two fields that depend on each other with Yup?

Solution: const yup = require('yup') const { setLocale } = yup setLocale({ mixed: { notType: 'the ${path} is obligatory', required: 'the field ${path} is obligatory', oneOf: 'the field ${path} must have one of the following values: ${values}' } }) const myNameSchema = yup. object(). shape({ first_name: yup.

How can I get validation error in Yup?

formatError(() => 'error', { path: 'path' }); // ValidationError let error: ValidationError = new yup. ValidationError('error', 'value', 'path'); error = new yup. ValidationError(['error', 'error2'], true, 'path'); error = new yup. ValidationError(['error', 'error2'], 5, 'path'); error = new yup.

How can I get parent value in Yup?

You can use the test method available in the https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema . like below example, you can access one level of parent details inside test() using this. parent.

What is Yup schema validation?

The Yup object schema provides two methods for validating: isValid and validate. isValid resolves true if the user submits a valid string, and false if an error exists in the string. validate returns an errors object if the input value is an invalid email.


1 Answers

@JQuense, the owner of the repo had an eloquent solution, using moreThan():

const schema = yup.object().shape({
    yearBuilt: yup
      .number()
      .integer()
      .min(1700)
      .max(currentYear+1)
      .required(),
    yearRenovated: yup
      .number()
      .integer()
      .nullable()
      .moreThan(yup.ref("yearBuilt")) //<-- a whole lot neater than using a when conditional...
      .max(currentYear+1)
});

Hope that helps! Thank you @JQuense.

like image 119
ZAR Avatar answered Sep 27 '22 22:09

ZAR