使用fastest-validator如何实现两个字段值不相等的校验?
fastest-validator没有内置的不等校验规则,你可以通过两种常用方式实现需求:
方案1:使用内置的custom校验规则直接实现
const Validator = require('fastest-validator'); const v = new Validator(); const schema = { _id: { type: "string", pattern: /^[0-9a-fA-F]{24}$/ }, // 适配MongoDB ObjectId格式 parent_id: { type: "string", pattern: /^[0-9a-fA-F]{24}$/, custom: (value, errors) => { // 获取当前校验对象的_id字段做比对 if (value === this.parent._id) { errors.push({ type: "notEqual", field: "parent_id", message: "parent_id不能与_id取值相等" }); } return value; } } }; const check = v.compile(schema); // 测试:两字段值相等的场景 console.log(check({ _id: "619e00c177f6ea2eccffd09f", parent_id: "619e00c177f6ea2eccffd09f" })); // 返回错误提示数组,校验不通过 // 测试:两字段值不等的场景 console.log(check({ _id: "619e00c177f6ea2eccffd09f", parent_id: "619e00c177f6ea2eccffd09e" })); // 返回true,校验通过
方案2:注册全局自定义notEqual类型,方便多场景复用
const Validator = require('fastest-validator'); const v = new Validator(); // 全局注册不等校验类型 v.add('notEqual', { validate: function(value, schema, path) { const targetField = schema.field; if (value === this.parent[targetField]) { return this.makeError( schema, path, "notEqual", `字段值不能与${targetField}相等`, value ); } return true; } }); // 直接使用自定义类型写校验规则,用法和内置的equal一致 const schema = { _id: { type: "string", pattern: /^[0-9a-fA-F]{24}$/ }, parent_id: { type: "notEqual", field: "_id" } }; const check = v.compile(schema); // 测试效果和方案1完全一致
内容的提问来源于stack exchange,提问作者Ali Shefaee
相关产品推荐
相关产品推荐

