我使用最快的驗證器來驗證這樣的物件:
{
"_id":"619e00c177f6ea2eccffd09f",
"parent_id": "619e00c177f6ea2eccffd09f",
}
_id并且parent_id不能相等。如何檢查?我知道fastest-validator有以下對等式的驗證。但我需要檢查相反的情況。(例如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
提前致謝
uj5u.com熱心網友回復:
根據自定義驗證器的元資訊:
您可以通過 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
}
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/367837.html
標籤:javascript 表达 验证
