Search code examples
asp.net-mvcvalidationunobtrusive-validation

Client side validation for custom attribute


Why is my client side validation not working.

Property is:

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

The validation attribute is:

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

In JS I have:

  $.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 and jquery.validate.unobtrusive.js are included


Solution

  • I'm not sure what you mean by "not working" but your jquery validation function appears to be oddly formed. I assume you want it to return false (aka invalid) if the value contains company.com anywhere. If so, your method should be something like:

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