Alex
Alex

Reputation: 9720

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

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

Upvotes: 1

Views: 12278

Answers (3)

Tanvir Ahammad Chy
Tanvir Ahammad Chy

Reputation: 126

Global Function,

export const minLengthValidation = (value: string | undefined, limit: number | undefined = 3) => {
  if (value && value.length < limit) {
    return false
  }

  return true
}

Invoked the function,

  nick_name: yup
    .string()
    .max(50, 'Nickname must be less than 50 characters!')
    .test('min-length', 'Nickname must be greater than  3 characters!', value => minLengthValidation(value))
    .required('Nickname is required.'),

Upvotes: 1

Max G.
Max G.

Reputation: 850

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));

Upvotes: 4

Alex
Alex

Reputation: 9720

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)))
                }
            ),

Upvotes: 1

Related Questions