Sir Rubberduck
Sir Rubberduck

Reputation: 2282

yup custom error messages not in ValidationError object

The yup ValidationError object doesn't have the custom error messages.

let data = {
    foo: "aaa"
}

let schema = 
    yup.object().shape({
        foo: yup.number().integer('Custom "must be a number" error message!')
    });

try {

    let validated = await schema.validate(data, { abortEarly: false })

} catch (err) {
    console.log(err.errors[0]) // foo must be a `number` type, but the final value was: `NaN`
    console.log(err.inner[0].message) // foo must be a `number` type, but the final value was: `NaN`
}

I should get Custom "must be a number" error message! at err.inner[0].message.

Here's the codesandbox.

What am I doing wrong? I'm doing it as shown here.

Upvotes: 3

Views: 18273

Answers (3)

Gel
Gel

Reputation: 3026

Today date is 2/8/2023, as per yup documentation, you can customize error message via test method chained after the yup object defenitions. Here is an example:

let PaymentSchema = yup.object({
    fullname: yup.string().required().test({
      name: 'fullname',
      skipAbsent: true,
      test(value, ctx) {
        if (!value.startsWith('Agent')) {
          return ctx.createError({ message: 'SKU missing correct prefix' })
        }
        if (!value.endsWith('-alpha-male')) {
          return ctx.createError({ message: 'SKU missing correct suffix' })
        }
        if (value.length < 10) {
          return ctx.createError({ message: 'SKU is not the right length' })
        }
        return true
      }
    })
  })

Upvotes: 0

Whisher
Whisher

Reputation: 32726

with 0.32.11 this seems to work:

string()
      .required('Email is require')
      .email('Email is not valid')

Upvotes: 0

Simon Bruneaud
Simon Bruneaud

Reputation: 2567

You should use try / catch block to catch async/await errors, like synchronous code.

Also you can't directly pass a message to the number() type function, instead you have to pass typeError

import * as yup from "yup";

const fn = async () => {
  let data = {
    foo: "a"
  };

  let schema = yup.object().shape({
    foo: yup.number().typeError("Custom not a number message!")
  });

  try {
    await schema.validate(data);
  } catch (e) {
    console.log(JSON.stringify(e));
  }
};

fn();

Upvotes: 11

Related Questions