每当我运行附带调试器的以下任一单元测试时,我都会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
我正在寻找一种方法来为Fluent验证实现不显眼的自定义验证.根据文档,它似乎并不表示它支持不显眼的验证.
同样适用于使用条件验证(When/unless).我在他们的MVC文档中看到,条件和其他复杂验证不支持不显眼的验证:
请注意,FluentValidation也适用于ASP.NET MVC的客户端验证,但并非所有规则都受支持.例如,使用条件(使用When/unless),自定义验证程序或对Must的调用定义的任何规则都不会在客户端运行.客户端支持以下验证器:
*NotNull/NotEmpty
*匹配(正则表达式)
*InclusiveBetween(范围)
*CreditCard
*电子邮件
*EqualTo(跨属性相等比较)
*长度
那么有没有人想出如何让这个工作?如果没有,是否有其他验证选项可以为不引人注目的自定义/复杂验证提供更好的支持?
asp.net-mvc fluentvalidation unobtrusive-validation asp.net-mvc-3
给定一个验证器扩展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
在我的ASP.NET MVC 4项目中,我有一个我的视图模型的验证器,它包含RuleSets的规则定义.Edit当所有客户端验证通过时,在Post操作中使用的规则集.Url和Email规则集规则集中使用的Edit规则(您可以在下面看到)和特殊的ajax操作,它们仅相应地验证电子邮件和仅验证Url.
我的问题是视图不知道它应该使用Edit规则集来生成客户端html属性,并使用default规则集,它是空的.如何判断视图使用Edit规则集进行输入属性生成?
模型:
public class ShopInfoViewModel
{
public long ShopId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Description { get; set; }
public string Email { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
验证器:
public class ShopInfoViewModelValidator : AbstractValidator<ShopInfoViewModel>
{
public ShopInfoViewModelValidator()
{
var shopManagementService = ServiceLocator.Instance.GetService<IShopService>();
RuleSet("Edit", () =>
{
RuleFor(x => …Run Code Online (Sandbox Code Playgroud) validation asp.net-mvc fluentvalidation unobtrusive-validation asp.net-mvc-4
在FluentValidation中是否有扩展或其他方式来推迟选择子验证器,具体取决于要验证的属性的类型/值?
我的情况是我有一个我要验证的Notification类.这个类有一个Payload属性,它可以是许多Payload类型之一,例如SmsPayload,EmailPayload等.这些Payload子类中的每一个都有自己的相关验证器,例如SmsPayloadValidator和EmailPayloadValidator.除上述内容外,核心库和个别通知提供者均未提及.从本质上讲,这意味着我可以根据需要添加提供程序,并使用IoC连接所有内容.
考虑以下类:
public class Notification
{
public Payload Payload { get; set; }
public IEnumerable<string> Details { get; set; }
}
public abstract class Payload
{
public string Message { get; set; }
public abstract string Type { get; }
}
public class SmsPayload : Payload
{
public List<string> Numbers { get; set; }
public string Region { get; set; }
public string Provider { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
有一个Notification验证器和SmsPayloadValidator如下:
public class NotificationValidator : AbstractValidator<Notification>
{
public NotificationValidator(IValidator<Payload> payloadValidator) …Run Code Online (Sandbox Code Playgroud) .net validation expression-trees fluentvalidation simple-injector
我对多个模型对象中的某些属性有类似的规则,我想用自定义属性验证器替换它们,以避免单元测试中的代码重复.
我有我的财产验证人:
public class IntIdPropertyValidator: PropertyValidator
{
public IntIdPropertyValidator()
: base("Property {PropertyName} should be greater than 0")
{
}
protected override bool IsValid(PropertyValidatorContext context)
{
var value = (int)context.PropertyValue;
return value > 0;
}
}
Run Code Online (Sandbox Code Playgroud)
并在模型验证器类中连接它:
public class SomeRequestValidator : AbstractValidator<CreateWordRequest>
{
public SomeRequestValidator()
{
RuleFor(x => x.Id).SetValidator(new IntIdPropertyValidator());
}
}
Run Code Online (Sandbox Code Playgroud)
试图测试:
[Test]
public void Validate_IdHasValidator_Success()
{
Init();
validator.ShouldHaveChildValidator(x => x.Id, typeof(IntIdPropertyValidator));
}
Run Code Online (Sandbox Code Playgroud)
但测试总是失败.
那么,我如何测试实际为属性Id设置的验证器?
例如,我有两个验证规则的验证器:
// Rule 1
RuleFor(o => o.Email).Must((email) => this.GetDataDataFromDB(email) != 0)
.WithMessage("User with provided Email was not found in database!");
// Rule 2
RuleFor(o => o.Email).Must((email) => this.GetDataDataFromDB(email) >= 1)
.WithMessage("There are multiple users with provided Email in database!");
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,使用相同的方法对数据库进行了两次调用.如何调用一次并将数据重用于其他规则?
显示错误消息时的另一个问题:
RuleFor(o => o.Email).Must((email) => this.GetDataDataFromDB(email) >= 1)
.WithMessage("There are multiple users with following Email '{0}' in database!",
(model, email) => { return email; });
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来显示错误消息,而不是一直写这些lambda表达式来检索属性?就像在某处保存模型一样,然后再使用它.
简单易行的解决方案会很棒!
这是我的验证类之一:
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中使用本地化和流畅的验证。这有什么好处。我在哪里可以找到好的教程?
fluentvalidation ×10
c# ×5
asp.net-mvc ×3
validation ×3
.net ×2
asp.net ×1
debugging ×1
exception ×1
html-helper ×1
intellitrace ×1
isrequired ×1
localization ×1
unit-testing ×1