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

假如想象 提交于 2020-06-26 04:12:17

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/54093909/how-to-test-for-uniqueness-of-value-in-yup-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!