客户端自定义验证与数据注释(MVC)

时间:2017-03-25 06:52:36

标签: jquery asp.net-mvc data-annotations unobtrusive-validation validate.js

我正在asp.net mvc中编写自定义验证器属性,它适用于服务器端验证。这是演示代码

 public class CustomEmailValidator : ValidationAttribute,IClientValidatable
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            string email = value.ToString();

            if (Regex.IsMatch(email, @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", RegexOptions.IgnoreCase))
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(ErrorMessage);//"Please Enter a Valid Email.");
            }
        }
        else
        {
            return new ValidationResult("" + validationContext.DisplayName + " is required");
        }
    }
    //new method
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
        rule.ValidationType = "emailvalidate";

        yield return rule;
    }
}

现在进行客户端验证,我无法将适配器添加到obstrusive.js。

$.validator.unobtrusive.adapters.add("emailvalidate", function (options) {

options.messages['emailvalidate'] = options.message;
    });

$.validator.addMethod("emailvalidate", function (value, element) {
     {
         console.log("inside emailValidate function");
         if (value=="test") {
             return true;
         }
         else {
             return false;
         }
    }

});

我不熟练添加适配器,所以我确定在向obstrusive.js添加适配器时存在问题。请指出这个问题。感谢。

0 个答案:

没有答案