Feeds:
Posts
Comments

Archive for the ‘MVC 4’ Category

Custom validation in MVC can be achieved in two ways by implementing :

  • ValidationAttribute class
  • IValidatableObject interface

ValidationAttribute

I have created a sample blog application which has a model blog class. Here i will create a validation for no of words in blogger name called MaxWord.

Below steps will demonstrate how to implement it:

  1. Create  class MaxWordAttribute which inherits from System.ComponentModel.DataAnnotations.ValidationAttribute 
  2. Override the IsValid() and add your validation logic here.
  3. Add the Attribute MaxWord(1) on the property (Blogger Name) in Model class
  1. Code1

Now run this and you will see the validations working perfectly.

Code2

But there is a catch here . The above validation will happen only at server side. To make it work at client side we need to do little thing extra.

Steps needed to make it work at client side :

  1. Make the MaxWordAttribute class implement IClientValidatable interface
  2. Implement GetClientValidationRule method. You can add custom parameters in this method that you require on client side for validation.MVC1

3. Create a JavaScript file and register your client methods here using jQuery.validator.unobtrusive.add and jQuery.validator.addMethod methods. I have created MyValidation.js and placed it under Scripts folder

.MVC2

4. To enable client-side validation we have to do couple of things. First we have to make sure  the ClientValidationEnabled and UnObtrusiveJavaScriptEnabled are set to true in web.config

Code5

5. The next thing is include the necessary javascript files in the layout page i.e in my case it is create.cshtml

Code4

Now you can have the custom validation at both client and server side 🙂

IValidatableObject

This is the approach you should use when you wanted to do a deep inspection of a model . Here you will be inside the model object and can access all the properties of the model.

Steps to implement it :

  1. Make your model class implement IValidatableObject interface
  2. Write your validation logic in the Validate() method

Code8

Code7

Unlike the simple IClientValidatable implementation required for the ValidationAttribute method, I have not found any way of enabling client-side validation when using IClientValidatable

Read Full Post »