自定义验证代码不会在离开焦点后立即触发
本文关键字:焦点 离开 代码 验证 自定义 | 更新日期: 2023-09-27 18:36:49
对于我的asp.net MVC View
,我使用验证注释和自定义验证器来验证我的字段。
在我的ViewModel
,
对于测试,我使用了
[StringLength(16, MinimumLength = 8, ErrorMessage = "This is a test to check if validation appears after leaving textbox")]
[Display(Name = "Requestor First Name")]
[Required]
public string RequestorFirstName { get; set; }
在视图中,当我只键入一个字母并离开文本框焦点时,将显示字符串长度的错误消息。我知道那件事客户端验证正在工作。
对于我的自定义验证器:
[FaceAmount]
public decimal CurrentFaceAmount { get; set; }
当我更改CurrentFaceAmount
字段中的美元金额时,它IMMEDIATELY
触发自定义验证代码。只点击"提交"按钮后,在以下代码中命中断点:
public class FaceAmount : ValidationAttribute, IClientValidatable
{
private string _dependentProperty;
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
decimal val;
var isNumeric = decimal.TryParse(value.ToString(), out val);
if (isNumeric)
{
if (val > 0 && val < 100000)
{
return new ValidationResult("Minimum Coverage Amount is $1000.00");
}
}
}
return ValidationResult.Success;
}
}
如何在离开文本框焦点后触发此自定义验证代码?
您必须添加一个如下所示的客户端验证器,由 Ode to Code 提供:
jQuery.validator.unobtrusive
.adapters.addSingleVal("greaterdate", "other");
jQuery.validator.addMethod("greaterdate",
function (val, element, other) {
var modelPrefix = element.name.substr(
0, element.name.lastIndexOf(".") + 1)
var otherVal = $("[name=" + modelPrefix + other + "]").val();
if (val && otherVal) {
if (Date.parse(val) <= Date.parse(otherVal)) {
return false;
}
}
return true;
}
);
并使用IClientValidatable链接到它:
public class DateGreaterThanAttribute :
ValidationAttribute,
IClientValidatable
{
public IEnumerable<ModelClientValidationRule>
GetClientValidationRules(ModelMetadata metadata,
ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationParameters.Add("other", OtherProperty);
rule.ValidationType = "greaterdate";
yield return rule;
}