Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use unobtrusive JS validation with custom validation attributes in MVC3?

I have this custom validation attribute called AsteriskRequiredAttribute which derives from the Required attribute and it's function is only to show an asterisk (*) when textbox field lacks value.

MVC3's unobtrusive JS validation seems to work perfectly out of the bow with the Required attribute but not with my custom attribute - nothing happens.

What goes?

like image 614
mare Avatar asked Dec 09 '25 13:12

mare


1 Answers

http://samipoimala.com/it/2010/11/29/unobtrusive-client-validation-in-asp-net-mvc-3/

It turns out that implementing a custom attribute is really an easy task. You implement your own class that inherits System.ComponentModel.DataAnnotations.ValidationAttribute and implements System.Web.Mvc.IClientValidatable. So you need to do three things.

1) Override public bool IsValid(object value) This method will be run when the validation is done on the server (for example, if the client does not have javascript enabled). This is all you need to do if you don’t need client validation.

2) Create a class that inherits from ModelClientValidationRule. This is usually very simple. Here’s an example how to enable email validation on the client:

public class ModelClientValidationEmailRule : ModelClientValidationRule
{
    public ModelClientValidationEmailRule(string errorMessage)
    {
        base.ErrorMessage = errorMessage;
        base.ValidationType = "email";
    }
}

3) Implement public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)

This is also usually very easy to implement, here’s the example on email validation:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    yield return new ModelClientValidationEmailRule(FormatErrorMessage(metadata.GetDisplayName()));
}

This is all you need do to write your own attribute to enable validation using the readymade validation rules on jQuery Validate plugin.

like image 149
kenwarner Avatar answered Dec 12 '25 11:12

kenwarner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!