fluentvalidation

内置验证程序

FluentValidation 有几个内置的验证器,这些验证器的错误消息都可以使用特定占位符。

NotNull 验证程序

说明:确保指定的属性不是 null。

RuleFor(customer => customer.Surname).NotNull();

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{PropertyValue} = 属性的当前值

NotEmpty 验证程序

说明: 确保指定的属性不是 null、空字符串或空格 (或值类型的默认值, 例如 int 0)。

RuleFor(customer => customer.Surname).NotEmpty();

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{PropertyValue} = 属性的当前值

NotEqual 验证程序

说明: 确保指定属性的值不等于特定值 (或不等于其他属性的值)

//Not equal to a particular value
RuleFor(customer => customer.Surname).NotEqual("Foo");

//Not equal to another property
RuleFor(customer => customer.Surname).NotEqual(customer => customer.Forename);

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{ComparisonValue} = 属性不应等于的值

Equal 相等验证程序

说明: 确保指定属性的值等于特定值 (或等于另一个属性的值)

//Equal to a particular value
RuleFor(customer => customer.Surname).Equal("Foo");

//Equal to another property
RuleFor(customer => customer.Password).Equal(customer => customer.PasswordConfirmation);

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{ComparisonValue} = 属性应相等的值
{PropertyValue} = 属性的当前值

Length 长度验证程序

确保特定字符串属性的长度位于指定范围内。但是, 它不能确保字符串属性是否为 null。

RuleFor(customer => customer.Surname).Length(1, 250); //must be between 1 and 250 chars (inclusive)

可用的格式参数占位符:

{PropertyName} = 正在验证的属性的名称
{MinLength} = 最小长度
{MaxLength} = 最大长度
{TotalLength} = 输入的字符数
{PropertyValue} = 属性的当前值

MaxLength 最大长度验证程序

说明:确保特定字符串属性的长度不超过指定的值。

RuleFor(customer => customer.Surname).MaximumLength(250); //must be 250 chars or fewer

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{MaxLength} = 最大长度
{TotalLength} = 输入的字符数
{PropertyValue} = 属性的当前值

MinLength 最小长度验证程序

说明:确保特定字符串属性的长度不能小于指定的值。

RuleFor(customer => customer.Surname).MinimumLength(10); //must be 10 chars or more

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{MinLength} = 最小长度
{TotalLength} = 输入的字符数
{PropertyValue} = 属性的当前值

LessThan 小于验证程序

说明: 确保指定属性的值小于特定值 (或小于另一个属性的值)

//Less than a particular value
RuleFor(customer => customer.CreditLimit).LessThan(100);

//Less than another property
RuleFor(customer => customer.CreditLimit).LessThan(customer => customer.MaxCreditLimit);

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{ComparisonValue}-属性比较的值
{PropertyValue} = 属性的当前值

LessThanOrEqualTo 小于等于验证程序

说明: 确保指定属性的值小于等于特定值 (或小于等于另一个属性的值)

//Less than a particular value
RuleFor(customer => customer.CreditLimit).LessThanOrEqualTo(100);

//Less than another property
RuleFor(customer => customer.CreditLimit).LessThanOrEqualTo(customer => customer.MaxCreditLimit);

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{ComparisonValue}-属性比较的值
{PropertyValue} = 属性的当前值

GreaterThan 大于验证程序

说明: 确保指定属性的值大于特定值 (或大于另一个属性的值)

//Greater than a particular value
RuleFor(customer => customer.CreditLimit).GreaterThan(0);

//Greater than another property
RuleFor(customer => customer.CreditLimit).GreaterThan(customer => customer.MinimumCreditLimit);

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{ComparisonValue}-属性比较的值
{PropertyValue} = 属性的当前值

GreaterThanOrEqualTo 大于等于验证程序

说明: 确保指定属性的值大于等于特定值 (或大于等于另一个属性的值)

//Greater than a particular value
RuleFor(customer => customer.CreditLimit).GreaterThanOrEqualTo(1);

//Greater than another property
RuleFor(customer => customer.CreditLimit).GreaterThanOrEqualTo(customer => customer.MinimumCreditLimit);

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{ComparisonValue}-属性比较的值
{PropertyValue} = 属性的当前值

Must 验证程序

描述: 将指定属性的值传递到一个委托中, 可以对该值执行自定义验证逻辑

RuleFor(customer => customer.Surname).Must(surname => surname == "Foo");

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{PropertyValue} = 属性的当前值

请注意, 委托参数不仅传递参数,还支持直接传递验证对象参数:

RuleFor(customer => customer.Surname).Must((customer, surname) => surname != customer.Forename)

正则表达式验证程序

说明: 确保指定属性的值与给定的正则表达式匹配,正则表达式可参阅正则表达式教程这篇文章

RuleFor(customer => customer.Surname).Matches("some regex here");

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{PropertyValue} = 属性的当前值

Email 电子邮件验证程序

说明: 确保指定属性的值是有效的电子邮件地址格式。

RuleFor(customer => customer.Email).EmailAddress();

可用的格式参数占位符:
{PropertyName} = 正在验证的属性的名称
{PropertyValue} = 属性的当前值

自定义验证程序

Must 验证程序

实现自定义验证程序的最简单方法是使用方法 Must 方法,假设我们有以下类:

public class Person {
  public IList<Person> Pets {get;set;} = new List<Person>();
}

为了确保列表中至少包含10个元素, 我们可以这样做:

public class PersonValidator:AbstractValidator<Person> {
  public PersonValidator() {
   RuleFor(x => x.Pets).Must(list => list.Count <= 10).WithMessage("The list must contain fewer than 10 items");
  }
}

为了使这种逻辑可重用, 我们可以将其封装为扩展方法。

public static class MyCustomValidators {
  public static IRuleBuilderOptions<T, IList<TElement>> ListMustContainFewerThan<T, TElement>(this IRuleBuilder<T, IList<TElement>> ruleBuilder, int num) {
    return ruleBuilder.Must(list => list.Count < num).WithMessage("The list contains too many items");
  }
}

在这里,我们通过为 IRuleBuilder 创建扩展方法实现可重用逻辑,使用方法很简单。

RuleFor(x => x.Pets).ListMustContainFewerThan(10);

编写自定义验证程序

如果您想灵活控制可重用的验证器, 则可以使用 Must 方法编写自定义规则,此方法允许您手动创建与验证错误关联的实例。

public class PersonValidator:AbstractValidator<Person> {
  public PersonValidator() {
   RuleFor(x => x.Pets).Custom((list, context) => {
     if(list.Count > 10) {
       context.AddFailure("The list must contain 10 items or fewer");
     }
   });
  }
}

此方法的优点是它允许您为同一规则返回多个错误。

context.AddFailure("SomeOtherProperty", "The list must contain 10 items or fewer");
// Or you can instantiate the ValidationFailure directly:
context.AddFailure(new ValidationFailure("SomeOtherProperty", "The list must contain 10 items or fewer");

自定义属性验证程序

在某些情况下, 针对某些属性的验证逻辑非常复杂, 我们希望将基于属性的自定义逻辑移动到单独的类中,可通过重写 PropertyValidator 类来完成。

using System.Collections.Generic;
using FluentValidation.Validators;
public class ListCountValidator<T> : PropertyValidator {
        private int _max;

    public ListCountValidator(int max)
        : base("{PropertyName} must contain fewer than {MaxElements} items.") {
        _max = max;
    }

    protected override bool IsValid(PropertyValidatorContext context) {
        var list = context.PropertyValue as IList<T>;

        if(list != null && list.Count >= _max) {
            context.MessageFormatter.AppendArgument("MaxElements", _max);
            return false;
        }

        return true;
    }
}

继承 PropertyValidator 时, 必须重写 IsValid 方法,此方法接受一个对象, 并返回一个布尔值, 指示验证是否成功,可通过 PropertyValidatorContext 属性访问:
Instance-正在验证的对象
PropertyDescription-属性的名称 (或者是由调用 WithName 的自定义的别名)
PropertyValue-正在验证的属性值
Member-描述正在验证的属性的 MemberInfo 信息

若要使用自定义的属性验证程序, 可以在定义验证规则时调用:

public class PersonValidator : AbstractValidator<Person> {
    public PersonValidator() {
       RuleFor(person => person.Pets).SetValidator(new ListCountValidator<Pet>(10));
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容