基于验证对象的自定义属性名称
我有以下课程,例如它们有点简化。
class LineInfo
{
Id,
LineNumber,
SubAccountNumer,
MobileNumber
}
class SuspendLinesVM{
public List<LineInfo> Lines{ get;set; }
}
我在操作中收到 SuspendLinesVM,并且所有线路都是从客户端动态创建的。表单中属于具体 LineInfo 的每个元素都具有模板“lineid{Id}_ElementName”的名称。因此,它们以如下形式来找我:
lineid0001_LineNumber
lineid0001_SubAccountNumer
lineid0001_MobileNumber
lineid0021_LineNumber
lineid0021_SubAccountNumer
lineid0021_MobileNumber
当验证时发生一些错误时,我需要一种方法来设置失败的属性,因为它是在请求中突出显示视图中的无效字段。
我留下了令我困惑的问题。
public class LineInfoValidator: AbstractValidator<LineInfo>
{
public LineInfoValidator()
{
RuleFor(m => m.LineNumber)
.NotEmpty().WithMessage("Line # is required").OverridePropertyName( ??? )
.InclusiveBetween(1, 9999).WithMessage("Line # must be in range [1, 9999]").OverridePropertyName( ??? )
...
我需要一种方法来做 *(instance, propertyName) => 之类的事情返回 string.format('lineid_{0}_{1}', instance.Id, propertyName)*。
有什么想法吗?
I have the following classes, they are bit simplified for example.
class LineInfo
{
Id,
LineNumber,
SubAccountNumer,
MobileNumber
}
class SuspendLinesVM{
public List<LineInfo> Lines{ get;set; }
}
I receive SuspendLinesVM in my action and all Lines are created dynamicaly from client. Each element that belongs to concrete LineInfo in form has name with template 'lineid{Id}_ElementName'. So they comes to me in form like:
lineid0001_LineNumber
lineid0001_SubAccountNumer
lineid0001_MobileNumber
lineid0021_LineNumber
lineid0021_SubAccountNumer
lineid0021_MobileNumber
When some error occures while validation, I need a way to set the failed property as it came in request to highlight invalid fields in the view.
I left questions where I got confused.
public class LineInfoValidator: AbstractValidator<LineInfo>
{
public LineInfoValidator()
{
RuleFor(m => m.LineNumber)
.NotEmpty().WithMessage("Line # is required").OverridePropertyName( ??? )
.InclusiveBetween(1, 9999).WithMessage("Line # must be in range [1, 9999]").OverridePropertyName( ??? )
...
I need a way to do something like *(instance, propertyName) => return string.format('lineid_{0}_{1}', instance.Id, propertyName)*.
Any ideas ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用“WithState”方法解决。感谢杰里米!他的解决方案在这里 http://fluidation.codeplex.com/discussions/278892
Resolved with 'WithState' method. Thanks to Jeremy! His solution is here http://fluentvalidation.codeplex.com/discussions/278892
鉴于您正在使用 FluentValidator,您应该能够在 SuspendedLinesVM 对象上设置集合验证器,如下所示:
如果您这样做,则 根据文档,您将得到与以下内容相关的错误集合失败属性的索引。
Given that you're using FluentValidator, you should be able to set the collection validator on the SuspendedLinesVM object like so:
If you do this, then as per the documentation you will get back a collection of errors which relate to the index of the failed property.