首页 > 其他 > 详细

FluentValidation

时间:2016-09-10 15:58:48      阅读:132      评论:0      收藏:0      [点我收藏+]

refer : 

https://www.exceptionnotfound.net/custom-validation-in-asp-net-web-api-with-fluentvalidation/

https://github.com/JeremySkinner/FluentValidation

这是一个开源的小工具,用来出来 model validation 

MVC,Web Api 都可以使用, Entity Framework 我就不太清楚 

我只用到 Web Api 的 ^^ 

 

这个工具是可以和原本的 data annotations validation 一起使用的

我是因为 ComplexType 需要不同的验证和需要 conditional 验证才选择这个工具的.

 

nuget : 

Install-Package FluentValidation.WebAPI

public static partial class Config
{   
    public static void Register(HttpConfiguration config)
    {
        FluentValidationModelValidatorProvider.Configure(config);     
    } 
}

基本用法 : 

[Validator(typeof(TestModelValidator))]
public class Test
{
    public Test()
    {
        this.address = new Address();
    }
    [Key]
    public int Id { get; set; }
    public string email { get; set; }
    public bool needValidAddress { get; set; }        
    public Address address { get; set; }
}
public class TestModelValidator : AbstractValidator<Test>
{
    public TestModelValidator()
    {
        RuleFor(x => x.address.text)
            .NotEmpty()
            .SetValidator(new CustomValidator<int>())
            .When(o => o.needValidAddress)
            .WithMessage("address text required");

        When(o => !string.IsNullOrWhiteSpace(o.email), () =>
        {
            RuleFor(c => c.email).Matches(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        });

        Custom(o => {
            return o.Id >= 10
                ? new ValidationFailure("Id","more than 10")
                : null;
        });
    }
}
public class CustomValidator<T> : PropertyValidator
{

    public CustomValidator()
        : base("Property {PropertyName} contains more than 10 items!")
    {

    }

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

        if (list != null && list.Count >= 10)
        {
            return false;
        }

        return true;
    }
}
[ComplexType]
public class Address
{
    public string text { get; set; }
}

 

FluentValidation

原文:http://www.cnblogs.com/keatkeat/p/5859541.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!