gpt4 book ai didi

asp.net-mvc - 基于验证对象的自定义属性名称

转载 作者:行者123 更新时间:2023-12-01 04:08:02 25 4
gpt4 key购买 nike

我有以下类(class),例如,它们有点简化。

class LineInfo
{
Id,
LineNumber,
SubAccountNumer,
MobileNumber
}

class SuspendLinesVM{
public List<LineInfo> Lines{ get;set; }
}

我在我的操作中收到 SuspendLinesVM,并且所有 Lines 都是从客户端动态创建的。表单中属于具体 LineInfo 的每个元素都具有模板名称“ ” lineid{Id}_ElementName '。所以他们以如下形式来找我:

lineid0001_LineNumber

lineid0001_SubAccountNumer

lineid0001_MobileNumber

lineid0021_LineNumber

lineid0021_SubAccountNumer

lineid0021_MobileNumber

当验证时发生一些错误时,我需要一种方法来设置失败的属性,因为它出现在请求中以突出显示 View 中的无效字段。

我在困惑的地方留下了问题。
 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) => return string.format('lineid_{0}_{1}', instance.Id, propertyName)* 的事情。

有任何想法吗 ?

最佳答案

用“WithState”方法解决。感谢杰里米!他的解决方案在这里http://fluentvalidation.codeplex.com/discussions/278892

JeremyS
Nov 10, 2011 at 5:16 PM

Unfortunately this isn't something that is supported.

Property names are resolved only once when the validator is instantiated, as opposed to error messages which are generated when the validator is executed. In this case, you need to inspect the instance being validated to generate the property name, which isn't actually possible - the closest you'd be able to get is to use the WithState method to associate some custom state with the failure:

RuleFor(x => x.LineNumber)
.NotEmpty()
.WithState(instance => string.Format("lineid_{0}_LineNumber", instance.Id));

Once you invoke the validator and get back the ValidationResult, you can retrieve this from the CustomState property on the ValidationFailure.

Jeremy

关于asp.net-mvc - 基于验证对象的自定义属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8081807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com