Home > Net >  fastest-validator: validate two field to not be equal
fastest-validator: validate two field to not be equal

Time:11-27

I use fastest-validator to validate an object like this:

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

_id and parent_id must not be equal. How to check that? I know fastest-validator has following validation for equality. but I need to check the opposite. (example for 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

Thanks in advance

CodePudding user response:

According to Meta information for custom validators:

You can pass any extra meta information for the custom validators which is available via context.meta.

so I can compare any two field that I want. In my to compare _id and parent_id I can use this:

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
        }
    }
};
  • Related