4

I am trying to implement custom attribute validation, similar to one demonstrated here in ScottGu's blog: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

I have this custom validator attribute for Email:

public class EmailAttribute : RegularExpressionAttribute
      {
      public EmailAttribute() :
                base("^[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})$") { }
      }

My class uses it like this:

    [Required(ErrorMessage = ValidationCiM.MsgObaveznoPolje)]
    [Email(ErrorMessage = ValidationCiM.MsgMailNeispravan)]
    [StringLength(ValidationCiM.LenSrednjePolje, ErrorMessage = ValidationCiM.MsgSrednjePolje)]
    public string Mail { get; set; }

and it all works well on server side, model is validated ok, and everything. But client side validation does not activate for this the second attribute, it works for Required, and it also works for StringLength but not for Email. i have tried including both jquery and Microsoft ajax scripts, but there seems to be no difference.

In ScottGu's blog, he states that the custom validation if implemented like this should work without the need to add custom script.

Any ideas please?

2 Answers 2

6

Use IClientValidatable in ASP.NET MVC 3:

 public class EmailAttribute : RegularExpressionAttribute, IClientValidatable
{
    public EmailAttribute()
      :base(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$")
    {

    }

    public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
      var rule = new ModelClientValidationRegexRule(this.ErrorMessageString, base.Pattern);
      return new[] { rule };
    }
  }
1
  • thank You, this has worked. I assume that for any custom rules it would only be necessary to implement the IClientValidatable interface with adequate rule type for it to be added to collection of rules jQuery can perform client validation for.
    – Zaak
    May 12, 2011 at 6:01
3

What you actually needed to do was this (on application start):

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));

It hooks up the client validation to your custom attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.