我有模型
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
我想创建一个验证,其中FirstName或LastName必须由用户填写。
我安装了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>
}
答案 0 :(得分:53)
您可以使用When/Unless条件:
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
适用于客户端验证,但并非所有规则都受支持。 Here您可以找到客户端支持的验证器:
对于不在列表中的规则,您必须编写自己的FluentValidationPropertyValidator
并实施GetClientValidationRules
。您可以通过简单搜索在StackOverflow上找到一些相关示例。
答案 1 :(得分:10)
试试这个
RuleFor(person => person).Must(person => !string.IsNullOrEmpty(person.FirstName) || !string.IsNullOrEmpty(person.LastName))
答案 2 :(得分:4)
我这样做是为了检查输入的费用是否与之前相同。 如果费用与之前的费用相同,则会产生错误。这对我有用。
public class CasualMealChargeValidator : AbstractValidator<CasualMealCharge>
{
public CasualMealChargeValidator(CasualMealCharge CMC)
{
//RuleFor(x => x.BankName).NotEmpty().When(pm => pm.PaymentMode == "Cheque").WithMessage("Enter Bank.");
RuleFor(x => x).Must(x => x.DN != CMC.DN || x.BF != CMC.BF || x.LN != CMC.LN).WithMessage("Not Saved - Meal charges are same as current charges.").WithName("CMFor");
}
}
答案 3 :(得分:3)
我不知道那个库,但是如果你只想检查这两个属性为null,那么你可以使用它:
RuleFor(person => person.FirstName ?? person.LastName).NotNull();
编辑这不起作用,因为它会抛出InvalidOperationException
。改为使用Zabavsky的解决方案。
答案 4 :(得分:1)
一个很好的规则集来检查两个字段中的一个是否为空,以及提出有意义的错误代码如下:
public CustomerSourceValidator()
{
CascadeMode = CascadeMode.StopOnFirstFailure;
RuleFor(x => x)
.NotNull().WithErrorCode("source_id_or_email_required")
.When(source => source.Email == null && source.Id == null);
RuleFor(x => x.Id)
.NotNull().WithErrorCode("source_id_required")
.Matches(CommonValidationRegex.CustomerIdRegexString).WithErrorCode("source_id_invalid")
.When(source => source.Id != null);
RuleFor(x => x.Email)
.NotNull().WithErrorCode("source_email_required")
.Matches(CommonValidationRegex.EmailRegexString).WithErrorCode("source_email_invalid")
.When(source => source.Email != null);
}
答案 5 :(得分:0)
最后,这对我有用。我想验证至少需要一个属性的三个属性。它仅返回一次错误消息。
RuleFor(p => p).Cascade(CascadeMode.StopOnFirstFailure)
.Must(p => !string.IsNullOrWhiteSpace(p.FirstName))
.When(p => p.Id == 0 && string.IsNullOrWhiteSpace(p.LastName)).WithMessage("At least one is required (Id, FirstName, LastName).")
.Must(p => !string.IsNullOrWhiteSpace(p.LastName))
.When(p => p.Id == 0 && string.IsNullOrWhiteSpace(p.FirstName)).WithMessage("At least one is required (Id, FirstName, LastName).")
.Must(p => p.Id != 0)
.When(p => string.IsNullOrWhiteSpace(p.FirstName) && string.IsNullOrWhiteSpace(p.LastName)).WithMessage("At least one is required (Id, FirstName, LastName).");