我有這個模式FluentValidation:檢查兩個領域之一是空
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
我想創造一個無論是名字或姓氏必須由用戶填寫驗證。 我安裝FluentValidation
創造了的CustomValidator類
public class PersonValidator:AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor((person=>person.FirstName)//don't know how to check if one is empty
}
}
要檢查只是一個領域我可能只是做RuleFor(person => person.FirstName).NotNull();
但我怎麼檢查,如果他們中的一個爲空。
此外,是否有可能通過fluentValidation
創建驗證,在客戶端使用它來顯示錯誤?
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>
}
什麼是'RequiredIfEmpty'屬性? – Zabavsky