Created
August 9, 2019 22:22
-
-
Save stephenway/19f46c2dca4cca601ed296e1ceeaec3d to your computer and use it in GitHub Desktop.
Unique Method for Yup Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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