Validation chain order
See original GitHub issueHi. Thank you for yup. We love yup much more than joi)
But we stacked with a problem which raised many times: https://github.com/jquense/yup/issues/113 https://github.com/jquense/yup/issues/251 https://github.com/jquense/yup/issues/256 https://github.com/jquense/yup/issues/499 https://github.com/jquense/yup/issues/503 https://github.com/jquense/yup/issues/602
Simple example:
We have an object with field user
. This field is required, should be valid MongoDB id and a user with this id should exist in the database.
const schema = yup.object({
user: yup.string()
.required()
.test(someMongoIdValidator)
.test({
message: () => 'user is not exists',
test: async (id) => {
const user = await User.findById(id);
return !!user;
},
}),
});
No sense to check if mongo id is valid for empty string and of course no sense to make database request (yes, it’s possible to return false if id is empty). We have cases with more reference fields and with arrays of references.
So, we just want to know - are there any plans to implement an option to keep the validation order? Is this consistent with the core idea of yup? Maybe it’s already planned and help is needed.
Or we just have to manage it by multiple schemas and something like “validation waterfall” - apply next schema with only valid fields from the previous schema and merge results at the end.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:36
- Comments:23 (2 by maintainers)
Top GitHub Comments
I think @codepunkt suggestion was elegant, with
.sequence()
: https://github.com/jquense/yup/issues/256#issuecomment-406807706That way it has to be explicitly enabled per rule group:
In the above case,
user
andpassword
would validate in parallel, as would the specific rules forpassword
, but the specific rules foruser
would execute sequentially. If.sequence()
was also added to the object schema, thenuser
andpassword
would also validate sequentially.Alternative names could be
sync()
,synchronous()
orsequenced()
.@gersondinis @jquense @ryall So, as above, a wrapper method called
sequence
can be like this:Then we can do this: