Home > Blockchain >  How to validate using yup to check string min length, max length and allow empty
How to validate using yup to check string min length, max length and allow empty

Time:12-31

firstName: yup
    .string()
    .test(
        'len',
        'can be empty or with string at least 2 characters and not more than 10',
        (val) => val != undefined && (val.length == 0 || (val.length >= 2 && val.length <= 10) )
    )

in this case length min 2 and max 10 works, but when is empty is marked with error i tried with val.length == 0

CodePudding user response:

fixed by separate undefined check

  firstName: yup
            .string()
            .test(
                'len',
                'can be empty or with string at least 2 characters and not more than 10',
                (val) => {
                    if (val == undefined) {
                        return true;
                    }
                    return  ((val.length == 0 || (val.length >= 2 && val.length <= 10)))
                }
            ),

CodePudding user response:

Hello you can do it like this

const yup = require("yup");
const firstName = "";

const schema = yup
  .string()
  .test(
    "len",
    "can be empty or with string at least 2 characters and not more than 10",
    (val) => {
      if (val === undefined) {
        return true;
      }
      return val.length === 0 || (val.length >= 2 && val.length <= 10);
    }
  );

schema
  .validate(firstName)
  .then((response) => console.log(response))
  .catch((err) => console.log(err));

  • Related