本文介绍了FluentValidation:检查两个字段之一是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个模型

 公共类人
{
public int ID {get;组; }
公用字串FirstName {get;组; }
公用字串LastName {get;组; }
}

我要创建一个必须填写名字或姓氏的验证按用户。
我安装了 FluentValidation 并创建了一个 customvalidator类

 公共类PersonValidator:AbstractValidator< Person> 
{
public PersonValidator()
{
RuleFor((person => person.FirstName)//不知道如何检查一个空的
}
}

要只检查一个字段,我可以做 RuleFor(person => person.FirstName).NotNull();



但是如何检查其中一个是否为空。 / p>

此外,是否可以通过 fluentValidation 创建验证后,在客户端使用它来显示错误?



Edit1

 受保护的无效Application_Start ()
{
AreaRegistration.RegisterAllAreas();

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
FluentValidationModelValidatorProvider.Configure();
}
//创建验证
命名空间WebApplic ation1.Models.CustomValidator
{
公共类PersonValidator:AbstractValidator< Person>
{
public PersonValidator()
{
RuleFor(m => m.FirstName).NotEmpty()。When(m => string.IsNullOrEmpty(m.LastName) ))。WithMessage( *必须是名或姓);
RuleFor(m => m.LastName).NotEmpty()。When(m => string.IsNullOrEmpty(m.FirstName))。WithMessage( *名字或姓氏为必填项);
}
}

}
//模型类
[Validator(typeof(PersonValidator))]
公共类Person
{
public Person()
{
InterestList = new List< string>();
}
public int Id {get;组; }
public int ContactId {get;组; }
[RequiredIfEmpty( LastName)]
公共字符串FirstName {get;组; }
[RequiredIfEmpty( FirstName)]
公共字符串LastName {get;组; }
公用字串EmailAddress {get;组; }
公用字符串Phone {get;组; }
公共字符串Country {get;组; }
公共列表< string> InterestList {get;组; }
}
//查看
@model WebApplication1.Models.Person

< script src = @ Url.Content(〜/ Scripts / jquery- 1.8.2.min.js)>< / script>
< script src = @ Url.Content(〜/ Scripts / jquery.validate.min.js)>< / script>
< script src = @ Url.Content(〜/ Scripts / jquery.validate.unobtrusive.min.js)>< / script>
< script src = @ Url.Content(〜/ Scripts / jquery.unobtrusive-ajax.min.js) type = text / javascript>< / script>

@ Html.ValidationSummary(true)
@using(Html.BeginForm( AddPerson, Person,FormMethod.Post))
{
< div class = label>名字< / div>
< div class = input-block-level> @ Html.TextBoxFor(m => m.FirstName)@ Html.ValidationMessageFor(m => m.FirstName)< / div>
< br />
< div class = label>姓氏< / div>
< div class = input-block-level> @ Html.TextBoxFor(m => m.LastName)@ Html.ValidationMessageFor(m => m.LastName)< / div>
< button type = submit class = btn-primary> Submit< / button>
}


解决方案

您可以使用条件:

  RuleFor(m => m.FirstName).NotEmpty()。When(m => string.IsNullOrEmpty(m.LastName)); 
RuleFor(m => m.LastName).NotEmpty()。When(m => string.IsNullOrEmpty(m.FirstName));

  RuleFor(m => m.FirstName).NotEmpty()。Unless(m =>!string.IsNullOrEmpty(m.LastName)); 
RuleFor(m => m.LastName).NotEmpty()。Unless(m =>!string.IsNullOrEmpty(m.FirstName));

对于第二个问题, FluentValidation 可以工作使用客户端验证,但不支持所有规则。 ,您可以找到客户端支持的验证器:


  1. NotNull / NotEmpty

  2. 匹配项(正则表达式)

  3. InclusiveBetween(范围)

  4. 信用卡

  5. 电子邮件

  6. EqualTo(跨属性平等比较)
  7. 长度

对于不在列表中的规则,您必须编写自己的 FluentValidationPropertyValidator 并实现 GetClientValidationRules 。通过执行简单搜索,您可以在上找到一些示例。


I have this model

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

I want to create a validation where either FirstName or LastName must be filled in by user.I installed FluentValidation and created a customvalidator class

public class PersonValidator:AbstractValidator<Person>
{
    public PersonValidator()
    {
        RuleFor((person=>person.FirstName)//don't know how to check if one is empty
    }
}

To check just one field I could just do RuleFor(person => person.FirstName).NotNull();

But how do I check if one of them is null.

Also, is it possible, once validation is created via fluentValidation, use it on the client side to show error?

Edit1

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        FluentValidationModelValidatorProvider.Configure();
    }
//creating validation
namespace WebApplication1.Models.CustomValidator
{
    public class PersonValidator:AbstractValidator<Person>
    {
        public PersonValidator()
        {
            RuleFor(m => m.FirstName).NotEmpty().When(m => string.IsNullOrEmpty(m.LastName)).WithMessage("*Either First Name or Last Name is required");
            RuleFor(m => m.LastName).NotEmpty().When(m => string.IsNullOrEmpty(m.FirstName)).WithMessage("*Either First Name or Last Name is required");
        }
    }

}
//model class
[Validator(typeof(PersonValidator))]
public class Person
{
    public Person()
    {
        InterestList = new List<string>();
    }
    public int Id { get; set; }
    public int ContactId { get; set; }
    [RequiredIfEmpty("LastName")]
    public string FirstName { get; set; }
    [RequiredIfEmpty("FirstName")]
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public string Phone { get; set; }
    public string Country { get; set; }
    public List<string> InterestList { get; set; }
}
//view
@model WebApplication1.Models.Person

<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

@Html.ValidationSummary(true)
@using(Html.BeginForm("AddPerson","Person",FormMethod.Post))
{
    <div class="label">First Name</div>
    <div class="input-block-level">@Html.TextBoxFor(m=>m.FirstName)@Html.ValidationMessageFor(m=>m.FirstName)</div>
    <br/>
    <div class="label">Last Name</div>
    <div class="input-block-level">@Html.TextBoxFor(m=>m.LastName)@Html.ValidationMessageFor(m=>m.LastName)</div>
    <button type="submit" class="btn-primary">Submit</button>
}
解决方案

You can use When/Unless condition:

RuleFor(m => m.FirstName).NotEmpty().When(m => string.IsNullOrEmpty(m.LastName));
RuleFor(m => m.LastName).NotEmpty().When(m => string.IsNullOrEmpty(m.FirstName));

or

RuleFor(m => m.FirstName).NotEmpty().Unless(m => !string.IsNullOrEmpty(m.LastName));
RuleFor(m => m.LastName).NotEmpty().Unless(m => !string.IsNullOrEmpty(m.FirstName));

As for your second question, FluentValidation works with client-side validation, but not all rules are supported. Here you can find validators, that are supported on the client-side:

  1. NotNull/NotEmpty
  2. Matches (regex)
  3. InclusiveBetween (range)
  4. CreditCard
  5. Email
  6. EqualTo (cross-property equality comparison)
  7. Length

For rules that are not in the list you have to write your own FluentValidationPropertyValidator and implement GetClientValidationRules. You can find a few samples of this on the StackOverflow by doing simple search.

这篇关于FluentValidation:检查两个字段之一是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:47