You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:24:03