C# 在ASP.NET MVC 2中,能否使用数据注释来比较表单中的两个字段?如果不是数据注释,还有哪些替代方案
我的表单中有两个字段 帐号 反向计数 我是否可以使用数据批注验证“ReverseAccountNumber”文本框的值是否等于“AccountNumber”的反转值 i、 e AccountNumber=12345 ReverseAccountNumber=54321 我希望在ReverseAccountNumber文本框的lostFocus事件上进行验证C# 在ASP.NET MVC 2中,能否使用数据注释来比较表单中的两个字段?如果不是数据注释,还有哪些替代方案,c#,asp.net-mvc,C#,Asp.net Mvc,我的表单中有两个字段 帐号 反向计数 我是否可以使用数据批注验证“ReverseAccountNumber”文本框的值是否等于“AccountNumber”的反转值 i、 e AccountNumber=12345 ReverseAccountNumber=54321 我希望在ReverseAccountNumber文本框的lostFocus事件上进行验证 我认为我可以使用IDATAError信息,但是我相信在验证生效之前,这将需要一个POST,并且我认为这是最后的选择。 < P>简单地将验证属
我认为我可以使用IDATAError信息,但是我相信在验证生效之前,这将需要一个POST,并且我认为这是最后的选择。
< P>简单地将验证属性添加到类(而不是属性)中,并评估Class对象来比较这两个属性。至于客户端,ASP.NET MVC 3应该能够为此生成适当的客户端验证(尽管我自己没有尝试过,因为Iam仍然使用xVal) 自定义属性[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class ReversStringMatchAttribute : ValidationAttribute
{
public string Property { get; set; }
public ReversStringMatchAttribute()
{ }
public override bool IsValid(object value)
{
return true;
}
}
自定义验证器
public class ReversStringValidator : DataAnnotationsModelValidator<ReversStringMatchAttribute>
{
string property;
public ReversStringValidator(ModelMetadata metadata, ControllerContext context, ReversStringMatchAttribute attribute)
: base(metadata, context, attribute)
{
property = attribute.Property;
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRule
{
ErrorMessage = Attribute.ErrorMessage,
ValidationType = "reversStringValidator"
};
rule.ValidationParameters.Add("propertyname", property);
return new[] { rule };
}
}
})
然后在你的财产上使用它
public class AccountViewModel
{
[Required(ErrorMessage="Account Number is Required")]
public string AccountNumber { get; set; }
[ReversStringMatch(ErrorMessage = "The value doesn't match the Account Number", Property="AccountNumber")]
public string ReverseAccountNumber { get; set; }
}
我对javascript中的$get验证方法有一些疑问,但目前它仍然有效。为什么在accountNumber失去焦点时不自动反转。@Adeel,业务规则类似于一些注册例程,您必须键入电子邮件,然后必须再次键入以确认。但是这里的区别不是只输入,而是你必须反向操作。对不起,我还没有将我的应用程序更新到ASP.NET MVC 3,所以我必须使用ASP.NET MVC 2解决方案(将编辑问题)。我想尝试类的Validation属性,这需要CustomValidator,对吗?你能找到一些示例链接来证明这一点吗?是的,我写了一篇关于这一点的博客文章:。其中一些引用了xVal,但其余部分也应该适用于您的场景。我不知道如何才能得到表单中的其他值。我陷入了必须添加验证参数的部分,我是否应该能够获得Validator类中“relevantProperties”的值?我在下面添加了我的答案。我发现您的解决方案对我来说仍然太复杂了,特别是Java脚本。但你确实把我引向了正确的方向。谢谢
public class AccountViewModel
{
[Required(ErrorMessage="Account Number is Required")]
public string AccountNumber { get; set; }
[ReversStringMatch(ErrorMessage = "The value doesn't match the Account Number", Property="AccountNumber")]
public string ReverseAccountNumber { get; set; }
}