[英]Check email validity with FluentValidation when property is not empty
[英]FluentValidation: Check if one of two fields are empty
我有這個模型
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>
}
您可以使用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
適用於客戶端驗證,但並非所有規則都受支持。 在這里,您可以找到客戶端支持的驗證器:
對於不在列表中的規則,您必須編寫自己的FluentValidationPropertyValidator
並實現GetClientValidationRules
。 您可以通過簡單搜索在StackOverflow上找到一些此示例。
試試這個
RuleFor(person => person).Must(person => !string.IsNullOrEmpty(person.FirstName) || !string.IsNullOrEmpty(person.LastName))
我這樣做是為了檢查輸入的費用是否與之前相同。 如果費用與之前的費用相同,則會產生錯誤。 這對我有用。
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");
}
}
我不知道那個庫,但是如果你只想檢查這兩個屬性為null,那么你可以使用這個:
RuleFor(person => person.FirstName ?? person.LastName).NotNull();
編輯這不起作用,因為它拋出InvalidOperationException
。 請改用Zabavsky的解決方案。
一個很好的規則集來檢查兩個字段中的一個是否為空,以及提出有意義的錯誤代碼如下:
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);
}
最后,這對我有用。 我想驗證三個屬性,其中至少需要一個屬性。 它只返回一次錯誤消息。
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).");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.