How to customize yup validation messages?
Asked Answered
B

3

13

Most answers I have seen customize yup validation messages when defining a schema, e.g.

const personSchema = yup.object().shape({
    firstName: yup.string().required('First name is a required field'),
    lastName: yup.string().required('Last name is a required field'),
});

But what if I want to customize the default validation message itself? For example, required fields should always render a fixed string "Required field".

Bricker answered 26/12, 2020 at 19:0 Comment(0)
C
19

You could do it by using setLocale function from yup like this:

  import * as Yup from 'yup';

  Yup.setLocale({
    mixed: {
      required: 'Required Field',
    },
  });

For more information check the documentation: https://github.com/jquense/yup

The section Using a custom locale dictionary is what you need.

Chatav answered 29/7, 2021 at 19:17 Comment(0)
F
3

I found that the accepted answer is correct but can be incomplete in some cases. Placing the cursor into a field and tabbing out of it can trigger a Yup "type error".

A default Yup type error is a verbose and non-user-friendly thing ;)

I would extend the answer from AndreasT to read:

const personSchema = yup.object().shape({
firstName: yup.string().required().typeError('first name is a required field'),
lastName: yup.string().required().typeError('Last name is a required field'),});
Fetch answered 25/3, 2023 at 9:20 Comment(0)
L
1

You do not need to do much. Just include your custom message for required inside the required function. You can also include separate messages for regex pattern

 fname: yup
      .string()
      .required('Please enter your first name *')
      .matches(
        /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/,
        "Enter valid first name !"
      ),
Loutish answered 17/7, 2023 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.