我使用SetCollectionValidator作为泛型集合.我的收藏是一个列表:
public class Answer {
public string QuestionConst { get; set; }
public string QuestionName { get; set; }
public bool Required { get; set; }
public string Answer { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我有验证设置和工作,所以当一个项目无效时,错误信息是这样的:"'QuestionName'不能为空".我想错误消息说"'第一个问题'不能为空." (其中第一个问题是其中一个项目的QuestionName的值).
我想我的问题是:是否可以在错误消息或属性名称中使用变量的值?
我正在使用FluentValidation,我想格式化一个对象的属性值的消息.问题是我对C#中的表达式和委托的经验很少.
FluentValidation已经提供了一种使用格式参数执行此操作的方法.
RuleFor(x => x.Name).NotEmpty()
.WithMessage("The name {1} is not valid for Id {0}", x => x.Id, x => x.Name);
Run Code Online (Sandbox Code Playgroud)
我想做这样的事情,以避免在我更改参数的顺序时更改消息字符串.
RuleFor(x => x.Name).NotEmpty()
.WithMessage("The name {Name} is not valid for Id {Id}",
x => new
{
Id = x.Id,
Name = x.Name
});
Run Code Online (Sandbox Code Playgroud)
原始方法签名如下所示:
public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(
this IRuleBuilderOptions<T, TProperty> rule, string errorMessage,
params Func<T, object>[] funcs)
Run Code Online (Sandbox Code Playgroud)
我在考虑为这个方法提供一个Func列表.
有人可以帮我这个吗?
我有一个MVC3视图模型定义为:
[Validator(typeof(AccountsValidator))]
public class AccountViewModel
{
public List<string> Accounts { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用FluentValidation(v3.3.1.0)定义验证为:
public class AccountsValidator : AbstractValidator<AccountViewModel>
{
public AccountsValidator()
{
RuleFor(x => x.Accounts).SetCollectionValidator(new AccountValidator()); //This won't work
}
}
Run Code Online (Sandbox Code Playgroud)
并且可能会定义帐户验证:
public class AccountValidator : AbstractValidator<string> {
public OrderValidator() {
RuleFor(x => x).NotNull();
//any other validation here
}
}
Run Code Online (Sandbox Code Playgroud)
我希望列表中的每个帐户都按照文档中的描述进行修改.但是,调用SetCollectionValidator不起作用,因为在使用a时这不是一个选项,List<string>尽管如果定义为选项将存在List<Account>.我错过了什么吗?我可以改变我的模型使用List<Account>然后定义一个Account类,但我真的不想改变我的模型以适应验证.
作为参考,这是我正在使用的视图:
@model MvcApplication9.Models.AccountViewModel
@using (Html.BeginForm())
{
@*The first account number is a required field.*@
<li>Account number* @Html.EditorFor(m …Run Code Online (Sandbox Code Playgroud) 我正在评估ServiceStack中的FluentValidation以处理请求DTO的自动验证:
Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof(MyValidator).Assembly);
Run Code Online (Sandbox Code Playgroud)
通过序列化ErrorResponseDTO 将错误返回给客户端,可能如下所示:
{
"ErrorCode": "GreaterThan",
"Message": "'Age' must be greater than '0'.",
"Errors": [
{
"ErrorCode": "GreaterThan",
"FieldName": "Age",
"Message": "'Age' must be greater than '0'."
},
{
"ErrorCode": "NotEmpty",
"FieldName": "Company",
"Message": "'Company' should not be empty."
}
]
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否可以使用不同的响应DTO返回错误.例如:
{
"code": "123",
"error": "'Age' must be greater than '0'."
}
Run Code Online (Sandbox Code Playgroud)
我知道可以在服务中明确使用验证器:
public MyService : Service
{
private readonly IValidator<MyRequestDto> validator;
public MyService(IValidator<MyRequestDto> validator)
{
this.validator = validator;
}
public …Run Code Online (Sandbox Code Playgroud) 我正在为我的Request对象定义一个验证.我希望验证器在第一次失败时停止,而不仅仅是同一链上的验证器.在下面的示例中,如果我的TechnicalHeader对象为null,则在验证达到规则时,我会收到NullReference异常TechnicalHeader.MCUserid.
可怜的话,根据第一条规则的结果,我想对下面代码中的最后三条规则进行条件验证
using System;
using ServiceStack.FluentValidation;
using MyProj.Services.Models;
namespace MyProj.Services.BaseService.Validators
{
public class BaseValidator<T> : AbstractValidator<T>
where T : RequestBase
{
public BaseValidator()
{
RuleSet(ServiceStack.ApplyTo.Put | ServiceStack.ApplyTo.Post,
() =>
{
this.CascadeMode = CascadeMode.StopOnFirstFailure;
RuleFor(x => x.TechnicalHeader).Cascade(CascadeMode.StopOnFirstFailure).NotNull().WithMessage("Header cannot be null");
RuleFor(x => x.TechnicalHeader).NotEmpty().WithMessage("Header cannot be null");
RuleFor(x => x.TechnicalHeader.Userid).NotEmpty().WithMessage("Userid cannot be null or an empty string");
RuleFor(x => x.TechnicalHeader.CabCode).GreaterThan(0).WithMessage("CabCode cannot be or less than 0");
RuleFor(x => x.TechnicalHeader.Ndg).NotEmpty().WithMessage("Ndg cannot be null or an empty string");
}
); …Run Code Online (Sandbox Code Playgroud) 我正在使用visual studio 2013和Fluent Validation 5.6.2
我看到在bin文件夹中构建之后,它会复制所有特定的文化FluentValidation.resources.dll,这些文化似乎是在.nuspec文件中提到的
> <file src="lib\NET35\de\FluentValidation.resources.dll"
> target="lib\NET35\de\FluentValidation.resources.dll" />
> <file src="lib\NET35\es\FluentValidation.resources.dll" target="lib\NET35\es\FluentValidation.resources.dll" />
> <file src="lib\NET35\fr\FluentValidation.resources.dll" target="lib\NET35\fr\FluentValidation.resources.dll" />
> <file src="lib\NET35\it\FluentValidation.resources.dll" target="lib\NET35\it\FluentValidation.resources.dll" />
> <file src="lib\NET35\nl\FluentValidation.resources.dll" target="lib\NET35\nl\FluentValidation.resources.dll" />
> <file src="lib\NET35\pt\FluentValidation.resources.dll" target="lib\NET35\pt\FluentValidation.resources.dll" />
> <file src="lib\NET35\sv\FluentValidation.resources.dll" target="lib\NET35\sv\FluentValidation.resources.dll" />
Run Code Online (Sandbox Code Playgroud)
但我不需要这些bin文件夹,因为项目不支持任何特定于文化的消息.
那么我怎么能告诉vs-build忽略这些特定文化的dll呢?
我尝试使用GreaterThen验证器,看起来它不支持客户端验证.是否有支持客户端验证的FluentValidation验证器列表?
这是我的ViewModel类:
public class CreatePersonModel
{
public string Name { get; set; }
public DateTime DateBirth { get; set; }
public string Email { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
CreatePerson.cshtml
@model ViewModels.CreatePersonModel
@{
ViewBag.Title = "Create Person";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
<fieldset>
<legend>RegisterModel</legend>
@Html.EditorForModel()
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Run Code Online (Sandbox Code Playgroud)
CreatePersonValidator.cs
public class CreatePersonValidator : AbstractValidator<CreatePersonModel>
{
public CreatePersonValidator()
{
RuleFor(p => p.Name)
.NotEmpty().WithMessage("campo obrigatório")
.Length(5, 30).WithMessage("mínimo de {0} e máximo de {1} caractéres", 5, 30)
.Must((p, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Autofac将依赖项注入MVC 4应用程序中的FluentValidation.我认为我的策略已经解决了,但是我已经陷入了解决单个问题的每个请求ISomething的问题.
这是场景:我有一个派生自FluentValidation的AbstractValidator的验证器.我已经读过FluentValidation验证器作为单例表现最好,所以我的构造函数需要一个Func并存储该Factory以供以后使用.使用验证器时,它应该向存储的工厂询问IDataStore,获取为该请求创建的实例并使用它.这就是理论.我想赞扬https://github.com/robdmoore/UnobtrusiveMVCTechniques,这有助于我解决这个问题.这是验证器......
public class SiteAdminViewModelValidator : AbstractValidator<SiteAdminViewModel> {
private readonly Func<IDataStore> _dbFactory;
public SiteAdminViewModelValidator(Func<IDataStore> dbFactory) {
_dbFactory = dbFactory;
RuleFor(model => model.SiteCode).Length(1, 40).Must(BeSpecial);
}
public bool BeSpecial(string siteCode) {
var db = _dbFactory();
List<Stuff> stuffs = db.All<Stuff>().ToList();
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人可以指出我正在努力完成的工作示例,那就太棒了,但我也想知道这个特定Autofac诡计的解决方案.
这是我的验证员注册...
public class FluentValidatorModule : Module {
protected override void Load(ContainerBuilder builder) {
base.Load(builder);
builder.RegisterType<AutofacValidatorFactory>().As<IValidatorFactory>().SingleInstance();
var validators = AssemblyScanner.FindValidatorsInAssembly(System.Reflection.Assembly.GetExecutingAssembly());
validators.ToList().ForEach(v => builder.RegisterType(v.ValidatorType).As(v.InterfaceType).SingleInstance());
}
}
Run Code Online (Sandbox Code Playgroud)
这是我在IDataStore工厂的注册......
builder.RegisterType<SuperDB>().As<IDataStore>().InstancePerHttpRequest();
builder.Register<Func<IDataStore>>(c => {
var context = c.Resolve<IComponentContext>();
return context.Resolve<IDataStore>; …Run Code Online (Sandbox Code Playgroud) 我正在使用一个在函数中使用参数的库,我需要使用该函数测试我的代码.
所以,试图通过我在该项目的其他部分使用的Moq来嘲笑我.
我知道下面有一面墙,所以问题(提前)是:
我认为这是模拟IXLRow接口的嘲弄方面的问题.通常看起来XLRow只是从工作簿中实例化而从不通过new XLRow()- 这是一个因素吗?
以下测试通过(注意:模拟):
[Fact]
public void TryGetValueCanReturnTrueForVieldWithAnInteger_WhenAccessingFromRow()
{
var workbook = new XLWorkbook();
workbook.Worksheets.Add("TestWS");
var wb = workbook.Worksheet("TestWS");
wb.Cell("A1").Value = "12345";
// NOTE: Here we're referring to the row as part of an instantiated
// workbook instead of Mocking it by itself
int output;
Assert.True(wb.Row(1).Cell("A").TryGetValue(out output));
}
Run Code Online (Sandbox Code Playgroud)
获取有效对象模拟的方法的片段():
// ...other code that sets up other parts of the row correctly
int isAnyInt = 0; //I don't care …Run Code Online (Sandbox Code Playgroud) fluentvalidation ×10
c# ×6
.net ×2
servicestack ×2
asp.net-mvc ×1
autofac ×1
datetime ×1
func ×1
linq ×1
mocking ×1
moq ×1
unit-testing ×1
validation ×1