fastest-validator:验证两个字段不相等
fastest-validator: validate two field to not be equal
我使用 fastest-validator 来验证这样的对象:
{
"_id":"619e00c177f6ea2eccffd09f",
"parent_id": "619e00c177f6ea2eccffd09f",
}
_id
和 parent_id
不能相等。如何检查?
我知道 fastest-validator
对 equality 进行了以下验证。但我需要检查相反的情况。
(type= "equal"
的示例):
const schema = {
password: { type: "string", min: 6 },
confirmPassword: { type: "equal", field: "password" }
}
const check = v.compile(schema);
check({ password: "123456", confirmPassword: "123456" }); // Valid
check({ password: "123456", confirmPassword: "pass1234" }); // Fail
提前致谢
根据Meta information for custom validators:
You can pass any extra meta information for the custom validators which is available via context.meta.
所以我可以比较我想要的任何两个字段。在我比较 _id
和 parent_id
时,我可以使用这个:
const v = new Validator({
useNewCustomCheckerFunction: true,
messages: {
notEqual: "_id and parent_id can not be equal"
}
});
const editSchema = {
_id: { type: "string" },
parent_id: {
type: "string",
custom: (value, errors, schema, name, parent, context) =>{
if (context.data._id === value) errors.push({type: "notEqual"})
return value
}
}
};
我使用 fastest-validator 来验证这样的对象:
{
"_id":"619e00c177f6ea2eccffd09f",
"parent_id": "619e00c177f6ea2eccffd09f",
}
_id
和 parent_id
不能相等。如何检查?
我知道 fastest-validator
对 equality 进行了以下验证。但我需要检查相反的情况。
(type= "equal"
的示例):
const schema = {
password: { type: "string", min: 6 },
confirmPassword: { type: "equal", field: "password" }
}
const check = v.compile(schema);
check({ password: "123456", confirmPassword: "123456" }); // Valid
check({ password: "123456", confirmPassword: "pass1234" }); // Fail
提前致谢
根据Meta information for custom validators:
You can pass any extra meta information for the custom validators which is available via context.meta.
所以我可以比较我想要的任何两个字段。在我比较 _id
和 parent_id
时,我可以使用这个:
const v = new Validator({
useNewCustomCheckerFunction: true,
messages: {
notEqual: "_id and parent_id can not be equal"
}
});
const editSchema = {
_id: { type: "string" },
parent_id: {
type: "string",
custom: (value, errors, schema, name, parent, context) =>{
if (context.data._id === value) errors.push({type: "notEqual"})
return value
}
}
};