rexroxm
rexroxm

Reputation: 878

React Yup validation for sum of length of two fields

I am new to React and yup validation. This is the entity

export interface ClientContact {
  names?: {
    firstName?: string;
    middleName?: string;
    lastName?: string;
  }[];
}

I don't want the name to be more than 75 characters i.e. sum of length of firstname, middlename and lastname cannot be more than 75.

const schema = Yup.object().shape({
    contacts: Yup.array().of(
      Yup.object().shape({
        names: Yup.array().of(
          Yup.object().shape({
            firstName: Yup.string()
              .required('First Name is required.')
              .max(45, 'Only 45 characters allowed.'),
            middleName: Yup.string(),
            lastName: Yup.string()
              .required('Last Name is required.')
              .max(45, 'Only 45 characters allowed.'),
          })
        ),
     });

How may I do that?

Upvotes: 2

Views: 1845

Answers (1)

Kostas Minaidis
Kostas Minaidis

Reputation: 5546

You can use the test method on the names Object:

const schema = Yup.object().shape({
  contacts: Yup.array().of(
    Yup.object().shape({
      names: Yup.array().of(
        Yup.object().shape({
          firstName: Yup.string()
            .required('First Name is required.')
            .max(5, 'Only 5 characters allowed.'),
          middleName: Yup.string(),
          lastName: Yup.string()
            .required('Last Name is required.')
            .max(5, 'Only 5 characters allowed.')
        // ADDITION >>
        }).test({
          message: 'The error message if length > 10',
          test: ({ firstName, middleName, lastName }) => {
            const len = firstName.length + middleName.length + lastName.length;
            console.log({ len });
            return len <= 10
          },
        })
        // << ADDITION
      )
    })
  )
});

schema
  .validate({ contacts: [
    { names: [{
      firstName: "John",
      middleName: "G.H.",
      lastName: "Doe"
    }] }
  ] })
  .catch(err => console.log(err.message))
  .then(() => console.log("valid"));

( Changed to a total of 10 for quick testing purposes. )

Upvotes: 2

Related Questions