您可以使用Fluent验证库验证单个属性吗?如果是,如何验证?我认为2009年1月的这个讨论主题向我展示了如何通过以下语法来实现:
validator.Validate(new Person(), x => x.Surname);
Run Code Online (Sandbox Code Playgroud)
不幸的是,它似乎不适用于当前版本的库.另一件让我相信可能有可能验证单个属性的事情是Jeremy Skinners博客文章的以下引用:
"最后,我添加了能够执行一些FluentValidation的属性验证器而无需验证整个对象的能力.这意味着现在可以停止将默认的"值为必需"消息添加到ModelState中."
但是,我不知道这是否必然意味着它支持仅验证单个属性,或者您可以告诉验证库在第一个验证错误后停止验证.
每当我运行附带调试器的以下任一单元测试时,我都会VerificationException在此时获得一个内部FluentValidation代码(如果需要,将在稍后发布整个堆栈跟踪):
at FluentValidation.Resources.LocalizedStringSource.CreateFromExpression(Expression`1 expression, IResourceAccessorBuilder resourceProviderSelectionStrategy)
in ...\FluentValidation\Resources\LocalizedStringSource.cs:line 66
Run Code Online (Sandbox Code Playgroud)
测试是:
using FluentValidation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var c = new MyClass();
var v = new MyValidator();
v.Validate(c);
}
[TestMethod]
public void TestMethod2()
{
Exception ex = null;
var done = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(
o =>
{
try
{
TestMethod1();
}
catch (Exception e)
{
ex = e;
}
finally
{
done.Set();
}
});
done.WaitOne(); …Run Code Online (Sandbox Code Playgroud) 我创建了一个HtmlHelper for Label,如果需要关联字段,则在该Label的名称后面放置一个星号:
public static MvcHtmlString LabelForR<TModel, TValue>(
this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
return LabelHelper(
html,
ModelMetadata.FromLambdaExpression(expression, html.ViewData),
ExpressionHelper.GetExpressionText(expression),
null);
}
private static MvcHtmlString LabelHelper(HtmlHelper helper, ModelMetadata metadata, string htmlFieldName, string text)
{
... //check metadata.IsRequired here
... // if Required show the star
}
Run Code Online (Sandbox Code Playgroud)
如果我在我的ViewModel中的属性上使用DataAnnotations和slap [Required],我的私有LabelHelper中的metadata.IsRequired将等于True,并且一切都将按预期工作.
但是,如果我使用FluentValidation 3.1并添加一个简单的规则:
public class CheckEmailViewModelValidator : AbstractValidator<CheckEmailViewModel>
{
public CheckEmailViewModelValidator()
{
RuleFor(m => m.Email)
.NotNull()
.EmailAddress();
}
}
Run Code Online (Sandbox Code Playgroud)
...在我的LabelHelper metadata.IsRequired将被错误地设置为false.(验证器有效:你不能提交空字段,它需要像电子邮件一样).
其余元数据看起来正确(例如:metadata.DisplayName ="Email").
理论上,如果使用Rule .NotNull(),FluentValidator会在属性上使用RequiredAttribute.
对于参考:我的ViewModel:
[Validator(typeof(CheckEmailViewModelValidator))]
public class CheckEmailViewModel
{
//[Required] …Run Code Online (Sandbox Code Playgroud) html-helper modelmetadata fluentvalidation asp.net-mvc-3 isrequired
给定一个验证器扩展AbstractValidator并实现IValidator,我想得到它的规则.似乎没有办法做到这一点?
我试图在流畅的验证库中使用动态消息构建自定义验证.
例如 :
public class CreateProcessValidator : AbstractValidator<CreateProcessVM>
{
public CreateProcessValidator()
{
RuleFor(x => x.ProcessFile).Must((x,e) => IsProcessFileValid(x.ProcessFile))).WithMessage("Parse failed with error : {0}");
}
public bool IsProcessFileValid(HttpPostedFileBase file)
{
var errorMessage = "..." // pass result to validaton message ?
// logic
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
在这里有任何解决方法如何传递验证结果?
谢谢
asp.net-mvc fluentvalidation fluentvalidation-2.0 asp.net-mvc-4
这是我的验证类之一:
public class StocksValidator : AbstractValidator<Stocks>
{
public StocksValidator()
{
RuleFor(x => x.SellerId).GreaterThan(1).WithMessage("SellerId should be greater than 1")
.LessThan(100).WithMessage("SellerId should be less than 100");
RuleFor(x => x.SellerType).GreaterThan(101).WithMessage("SellerType should be greater than 101")
.LessThan(200).WithMessage("SellerType should be less than 200");
RuleFor(x => x.SourceId).GreaterThan(201).WithMessage("SourceId should be greater than 201")
.LessThan(300).WithMessage("SourceId should be less than 300");
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这些消息,例如{field}应该少于{x}应该位于公共位置,而不是这里。但是我不知道如何集中他们?
一种方法是使用所有这些常量字符串创建新的c#文件。这很简单。
在Web API中使用本地化和流畅的验证。这有什么好处。我在哪里可以找到好的教程?
我有一个模特:
public class DTO
{
public int[] StatementItems { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我要验证的是:
StatementItems 不是空的StatementItems 不是空的 StatementItems 不包含任何重复的ID我创建的验证规则链是:
RuleFor(x => x.StatementItems).NotNull().NotEmpty().Must(x => x.Distinct().Count() == x.Count());
Run Code Online (Sandbox Code Playgroud)
我有一个测试:
_validator.ShouldHaveValidationErrorFor(x => x.StatementItems, null as int[]);
Run Code Online (Sandbox Code Playgroud)
当我运行测试传递一个空值时,我希望它在chain(NotNull())的第一个规则上失败并停在那里.但是,它抱怨使用的lamda值为Must()null.
我认为Must()如果NotNull()失败不应该运行我错了吗?如果是这样,该规则应如何编写?
谢谢
在FluentValidation.NET之前,我可以像这样正确地给一个自定义标签:
[Display(Name="Blah")]
public string BlahBlahBlah { get; set; }
Run Code Online (Sandbox Code Playgroud)
我可以通过多种方式消耗它:
@Html.LabelFor(m => m.BlahBlahBlah)
@Html.DisplayNameFor(m => m.BlahBlahBlah)
<label asp-for="BlahBlahBlah"></label>
Run Code Online (Sandbox Code Playgroud)
现在我想从我的模型中删除所有数据注释,并转向流畅的验证。在我的验证器中,我有这个:
RuleFor(o => o.BlahBlahBlah)
.NotEmpty()
.WithName("Blah");
Run Code Online (Sandbox Code Playgroud)
但这不起作用。为什么?
开箱即用,当 FV 检测到验证失败时,它会以数组形式显示属性名称、错误消息、尝试值,并将其作为 BadRequest 响应返回。
然而,FV 的 validator.Validate() 方法实际上返回一个更丰富的 ValidationResult 对象,并包含有关错误代码和参数化值的元数据。
我希望能够返回实际的 ValidationResult,包括所有丰富的元数据,而不仅仅是验证失败的一些数据。
我怎样才能改变这种行为?(.net core 2.1 顺便说一句)。
我正在努力为一个类实现一个验证器,其中应该只设置一个属性。
假设我们有以下类:
public class SomeClass
{
public DateTime SomeDate {get; set;}
public IEnumerable<int> FirstOptionalProperty {get; set;}
public IEnumerable<int> SecondOptionalProperty {get; set;}
public IEnumerable<int> ThirdOptionalProperty {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
这个类有一个强制性属性 - SomeDate。其他属性是可选的,只能设置一个,例如如果FirstOptionalProperty设置了 -SecondOptionalProperty并且ThirdOptionalProperty应该为空,如果SecondOptionalProperty设置了 -FirstOptionalProperty并且ThirdOptionalProperty应该为空等等。
换句话说:如果设置了 IEnumerable 道具之一 - 其他 IEnumerables 应该为空。
关于为此类类实现验证器的任何提示/想法?我唯一想到的是编写When规则块,但是这种编写代码的方式很容易出错,而且结果看起来很丑陋。
fluentvalidation ×10
c# ×6
asp.net-mvc ×3
.net ×2
asp.net ×2
asp.net-core ×2
validation ×2
.net-core ×1
debugging ×1
exception ×1
html-helper ×1
intellitrace ×1
isrequired ×1
localization ×1