Pages

Friday 4 April 2014

Validation using Attributes in mvc4


Here I am going to show you how to set validation on different form control without writting single line of javascript code.

In mvc4 there are different attributes which are used to perform different types of validations.

Following are the Few Attributes:

Required : Ensures that a property has been assigned some value. Range : Ensures that a property value falls within a minimum and maximum value. StringLength : Can be used to check the length of a string property. You can either specify maximum permissible length or maximum and minimum permissible length. EmailAddress : Validates that an email address with a valid email format has been supplied as a property value. Url : Validates that a valid URL has been supplied as a property value. RegularExpression : Uses a regular expression to ensure that a property value matches the specified pattern.

To apply validation create class into model folder(or in case of you are using layered architecture then in the Entity layer) and give the meaning full name such as "Validations.cs" this class contains all the code related to your validation on different form element. This validation is recommended to use only when your view elements are strongly typed.

Validation.cs Class:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;

namespace Distribution.Entities
{
    [MetadataType(typeof(IrdMasterMeatadata))]
    public partial class IrdMaster
    {
    }

    public class IrdMasterMeatadata
    {
        [Required]
[StringLength(50, MinimumLength = 3, 
ErrorMessage = "IrdCode must be between 3 and 50 characters!")]
        public string IrdCode { get; set; }
    }

    [MetadataType(typeof(VcMasterMeatadata))]
    public partial class VcMaster
    {
    }

    public class VcMasterMeatadata
    {
        [Required]
        public string VcCode { get; set; }
    }
}

In above code I used the partial class which was already implemented in Designer.cs file. The reason behind the reimplementation of partial class instead of writing the validation code into designer.cs file is that if we updated our .edmx file then Designer.cs file also get modified.

Here IrdMaster is the Database table whose partial class is created into designer.cs file when we add entity into the project. And IrdCode is the primitive property of the class IrdMaster and I am applying the [Required] attribute which is used to for showing error message when user is going to submit the form without entering any value into the IrdCode field. Also I used StringLength attribute for giving error message if user not enter value less than or greater than the specified value. Here I also used MetadataType attrinute on partial class irdMaster. The [MetadataType] attribute accepts the type of the class that is supplying metadata information to the IrdMaster class (IrdMasterMetadata in this case).

Here I also applied validations for VcCode class also. So similarly here you can specify number of class at a time on single validation.cs class. And apply validations on there primitive attributes.

Client Side validation:

This attribute is used to perform both client side as well as server side validations. To make same validations work on client side add following script file in the same order on your view. It's better to add this file on your Layout to avoid repeated reference on each view.

 <script src="~/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
 <script src="~/Scripts/jquery.validate.js" type="text/javascript"></script>
 <script src="~/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
To make this validation work check this setting into web.config file
    <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
Validation output:

No comments:

Post a Comment