离开焦点后不会立即触发自定义验证码

时间:2016-02-29 18:27:13

标签: c# asp.net asp.net-mvc

对于我的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; }

在视图中,当我只键入一个字母并保留文本框焦点时,会出现stringlength的错误消息。我知道 客户端验证正在运行。

我的自定义验证器:

[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;
    }
}

如何在离开文本框焦点后触发此自定义验证码?

1 个答案:

答案 0 :(得分:1)

您必须添加一个看起来像这样的客户端验证器,由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;
    }