自定义属性的客户端验证

时间:2015-07-29 16:04:32

标签: asp.net-mvc validation unobtrusive-validation

为什么我的客户端验证无效。

财产是:

  [Required(ErrorMessage = "Email address is required")]
  [EmailAddress(ErrorMessage = "Invalid Email Address")]
  [NonCompanyEmailAttribute(ErrorMessage = "Email address of customer required (not company employees)")]
        public string EmailAddress

验证属性为:

public class NonCompanyEmailAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        bool containscompany = !((string)value).ToLower().Contains("@company.com");
        return containscompany;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "noncompanyemail"
        };
    }
}

在JS中我有:

  $.validator.addMethod("noncompanyemail", function (value, element, params) {
            return value.toLowerCase().indexOf('company.com' > -1);
        });


        $.validator.unobtrusive.adapters.add("noncompanyemail", function (options) {
            options.rules["noncompanyemail"] = true;
            options.messages["noncompanyemail"] = options.message;
        });

包含jquery.validate.js和jquery.validate.unobtrusive.js

1 个答案:

答案 0 :(得分:1)

我不确定你的意思&#34;没有工作&#34;但是你的jquery验证函数看起来很奇怪。如果值包含company.com,我假设您希望它返回false(也称为无效)。如果是这样,您的方法应该是:

$.validator.addMethod("noncompanyemail", function (value, element, params) {
            return (value.toLowerCase().indexOf('company.com') == -1);
        });