Yup: Validate a field with an alias in error

Created on 19 Jan 2018  路  2Comments  路  Source: jquense/yup

I'd like to validate an object schema that has a property X but on the error template I want it to change the name of the property to Y

const yup = require('yup');
const { setLocale } = require('yup/lib/customLocale');

setLocale({
  mixed: {
    notType: 'O campo ${path} deve ser um ${type}',
  }
});

const obj = {X:1, Z:"1"};

const validateObj = object => yup.object({
 X: yup.string().required,
 Z: yup.number().required,
}).validate(object, { abortEarly: false, strict: true }))

(async () => {
  try {
    await validateObj(obj);
  } catch (e) {
      return Promise.reject({
        message: { errors: err.errors },
      });
  }
})();

would return

"message": {
            "errors": [
                "O campo X deve ser um string",
                "O campo Z deve ser um number"
            ]
        }

I'd like it to return the name of the value with an alias Y

"message": {
            "errors": [
                "O campo Y deve ser um string",
                "O campo Z deve ser um number"
            ]
        }

Most helpful comment

I believe you should use .label() for that:

Yup.object().shape({
    downPayment: Yup.number()
        .required()
        .positive()
        .min(0)
        .max(10000)
        .label('Your down payment'),
})

This gives me messages like Your down payment must be greater than or equal to 0

All 2 comments

I'm missing that as well!

I believe you should use .label() for that:

Yup.object().shape({
    downPayment: Yup.number()
        .required()
        .positive()
        .min(0)
        .max(10000)
        .label('Your down payment'),
})

This gives me messages like Your down payment must be greater than or equal to 0

Was this page helpful?
0 / 5 - 0 ratings