pavanarya

Let us share the knowledge

DataAnnotations to perform validations at client side

leave a comment »

Hi in this post i want to write about data annotations which is used to set validation rules in the model level that reflects at client side(view or html).

DataAnnotations is a powerful and beautiful concept. By default dataannotations were introduced in framework 4.0 and if we want to have these dataannotations in previous frameworks we can download the dll from this url and use that in our project.
With dataannotations we can perform following validations at client side:

List of validations supported
CreditCardAttribute
CuitAttribute
DateAttribute
DigitsAttribute
EmailAttribute
EqualToAttribute
FileExtensionsAttribute
IntegerAttribute
MaxAttribute
MinAttribute
NumericAttribute
UrlAttribute
YearAttribute

Creating a Model with some properties and validations

System.ComponentModel.DataAnnotations is the namespace that contains required classes and methods to perform validations.

We are suppsoed to decorate our model class properties with these classes and methods.

If we see below code we are decorating our property firstname as required and also specifying the maxlength it accepts. If it exceeds max length we are showing an error message.

In the same way AddressCity as non editable, setting range fro experience.

MyModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication2.Models
{
    public class MyModel
    {
        [System.ComponentModel.DataAnnotations.Required]
        [System.ComponentModel.DataAnnotations.MaxLength(3,ErrorMessage="Please enter correct value")]
        public string firstname { set; get; }

        [Required]        [System.ComponentModel.DataAnnotations.CustomValidation(typeof(MvcApplication2.Models.MyModel),"ValidateLastName")]
        public string lastname { set; get; }

        [Required]
        [System.ComponentModel.DataAnnotations.Editable(false)]
        public string AddressCity { set; get; }

        public string FullName { set; get; }

        [Required]
        [System.ComponentModel.DataAnnotations.Range(1,10)]
        public int experience { set; get; }


        [Required]
        [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
        public string nicknameFirstNmae { set; get; }
        public string profession { set; get; }
        public string designation { set; get; }
        

        public static System.ComponentModel.DataAnnotations.ValidationResult ValidateLastName(object value, ValidationContext context)
        {
            return new ValidationResult("This is to test custom validation");
        }
    }
}

Creating a custom validation method and assigning that to a property

A part from existing validation classes and methods we can also create custom methods that are supposed to generate the error based on some criteria.

If we see our model class, there is a property called “lastname”

[Required]        [System.ComponentModel.DataAnnotations.CustomValidation(typeof(MvcApplication2.Models.MyModel),"ValidateLastName")]
        public string lastname { set; get; }

So here lastname was decorated with “System.ComponentModel.DataAnnotations.CustomValidation”. it contains two parameters
i. Type that contains the custom method
ii. name of the custom method.

In this case we are creating a custom method “validateLastName” in the class MyModel.
The custom method should follow these rules
i. It should be a static method
ii. return type should be of type “System.ComponentModel.DataAnnotations.ValidationResult”
iii. It should accept 2 parameters
a. an object that contains value
b.ValidationContext(which describes the context in which validation is to be performed)
iV. should return new ValidationResult(string errormsg);

 public static System.ComponentModel.DataAnnotations.ValidationResult ValidateLastName(object value, ValidationContext context)
        {
            return new ValidationResult("This is to test custom validation");
        }

Now we are done with our changes in model class. Now let us go to our controller.

Controller changes
In our controller let us create 2 action methods with the name “Create”. ofcourse one is supposed to be decorated with [HttpPost] to handle the button click events and other to generate the view on request.

FirstController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Web.Mail;
using System.Dynamic;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Linq.Expressions;
using System.Diagnostics;

namespace MvcApplication2.Controllers
{
    public class FirstController : Controller
    {

        public ActionResult Create()
        {
            return View(new MvcApplication2.Models.MyModel());
        }

        [HttpPost]
        public ActionResult Create(MvcApplication2.Models.MyModel user)
        {
            if (!ModelState.IsValid)
            {
                return View(user);
            }

            return Content("User valid!");
        }
    }
}

In our Create method decorated with [HttpPost] we are checking for ModelState IsValid property. This is set to true if all the data entered at client side is valid else this will be false.

View

Now coming to our view the first and foremost thing that we are supposed to do is enabling client side validation. If this is not done then validations will be performed at server side.
To enable this we use Html.EnableClientValidation();

Next important thing is to include required js files. If we dont include required js files, validation will be performed at server side.

<script src="../../Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
  <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
   <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
   <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
   <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

Now render a form elements that contains model properties as text fields using @Html.EditForModel().
Now keep these text boxes inside the form using “@using (Html.BeginForm())”

Create.cshtml

@model MvcApplication2.Models.MyModel
 
@{
    ViewBag.Title = "Create";
    Html.EnableClientValidation();
}

<h2>Create</h2>
 
 <script src="../../Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
  <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
   <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
   <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
   <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User</legend>
        
        @Html.EditorForModel()
        
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

Now if we violate the validations specified inside the model then it will show us an error message immediately on blur or mouse out event.

So developers can skip some validation code blocks inside javascript :)

Thanks,
pavan

About these ads

Written by pavanarya

July 14, 2012 at 11:42 pm

Posted in MVC

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 68 other followers

%d bloggers like this: