3

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.