Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup - Output a field value in the error message

Tags:

javascript

yup

I am trying to output the field value in the error messaging doing something like this:

const schema = commonSchema.concat(Yup.object().shape({
  name: Yup
    .string()
    .oneOf(
      [Yup.ref('oldName'), null],
      `Name must match oldName - ${Yup.ref('oldName').getValue()}`
    )
    .required('name'),
}));

This is giving TypeError: Cannot read property 'parent' of undefined. What is the right way to access the field value in an error message?

like image 359
Mike Avatar asked Nov 06 '22 10:11

Mike


1 Answers

The trick I use to get the value into error message is to use yup.lazy method.

yup.lazy((value: any) => Schema): Lazy

In your case it would look something like this,

const schema = commonSchema.concat(Yup.object().shape({
  name: Yup.lazy((value) => 
    Yup.string()
    .oneOf(
      [Yup.ref('oldName'), null],
      `Name must match oldName - ${value}`
    )
    .required('name')),
}));
like image 157
Luke Celitan Avatar answered Nov 14 '22 22:11

Luke Celitan