Skip to content

Instantly share code, notes, and snippets.

@stephenway
Created August 9, 2019 22:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenway/19f46c2dca4cca601ed296e1ceeaec3d to your computer and use it in GitHub Desktop.
Save stephenway/19f46c2dca4cca601ed296e1ceeaec3d to your computer and use it in GitHub Desktop.
Unique Method for Yup Validation
/*
* Author: @carlosagsmendes
* Source: https://github.com/jquense/yup/issues/345#issuecomment-487320558
*/
import yup from 'yup';
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;
});
});
const validationSchema = yup.object().shape({
people: yup
.array()
.of(
yup.object().shape({
phone: yup.number(),
firstName: yup.string().max(10),
lastName: yup.string().min(2)
})
)
.unique('duplicate phone', a => a.phone)
.required("Must have friends")
.min(3, 'Minimum of 3 friends'),
// these constraints are shown if and only if inner constraints are satisfied
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment