fastest-validator:验证两个字段不相等

fastest-validator: validate two field to not be equal

我使用 fastest-validator 来验证这样的对象:

{
    "_id":"619e00c177f6ea2eccffd09f",
    "parent_id": "619e00c177f6ea2eccffd09f",
}

_idparent_id 不能相等。如何检查? 我知道 fastest-validatorequality 进行了以下验证。但我需要检查相反的情况。 (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.

所以我可以比较我想要的任何两个字段。在我比较 _idparent_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
        }
    }
};