Search code examples
javascriptvalidationformikyup

How to test for uniqueness of value in Yup.array?


I have form with dynamic amount of inputs (admin email) however checking for uniqueness fails:

      validationSchema={Yup.object().shape({
        adminEmails: Yup.array()
          .of(
            Yup.string()
              .notOneOf(Yup.ref('adminEmails'), 'E-mail is already used')

What is best approach here? FYI, as a form helper I use Formik.


Solution

  • Try this:

    Yup.addMethod(Yup.array, 'unique', function(message, mapper = a => a) {
        return this.test('unique', message, function(list) {
            return list.length  === new Set(list.map(mapper)).size;
        });
    });
    

    Then use it like this:

    const headersSchema = Yup.object().shape({
        adminEmails: Yup.array().of(
            Yup.string()
        )
        .unique('email must be unique')
    })