![](/img/trans.png)
[英]FluentValidation : Is it possible to add a RuleSet while invoking a validator using ValidateAndThrow
[英]Fluentvalidation Validator for multiple possible values
Fluentvalidation是否有任何內置的 function 來驗證多個可能的選項以通過/失敗,類似於 SQL In 運算符?
例如:在下面的代碼中,我需要確保 user_status 必須是 ("Active", "Expired", "Blocked"......................) 等。
而對於 user_role 它應該是 user_role("admin", "manager", "viewer"......)
public class Users
{
public string user_status { get; set; }
public string user_role { get; set; }
}
public class UpdateUserValidator : NullReferenceAbstractValidator<Users>
{
public UpdateUserValidator()
{
RuleFor(user => user.user_status).NotNull();
}
}
據我所知,沒有內置的驗證器可以這樣做。
您可以使用.Must
和一組接受的值。
這樣的事情(當然,接受值的集合可以在變量中,並在must和message部分中使用)。
RuleFor(x =>x.user_status)
.Must(x => new[]{"Active", "Expired", "Blocked"}.Contains(x))
.WithMessage("User status should be either 'active', 'expired' or 'blocked'");
或者,您當然可以創建自己的自定義驗證程序。
接受的答案中的代碼片段對我不起作用,我使用的工作規則是
RuleFor(_ => _.user_status)
.Matches(@"^(Active|Expired|Blocked)")
.WithMessage("User status should be either 'active', 'expired' or 'blocked'");
流暢驗證 11.2.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.