Saturday, April 21, 2012

Simple client-side Validations using ASP.NET MVC

This article aims to demonstrate how we can apply simple validations at view (page) level in ASP.NET MVC.

Say, you have a "Person" model, that you pass in the view to and fro controller action.

A Person model is having many fields, one of them is "PersonName" (Label: Person Name) and you want to make it required when user inputs data in corresponding view of this model.

In order to achieve this, first decorate PersonName field in Person model with "Required" attribute.
"Required" attribute is a part of System.ComponentModel.DataAnnotations namespace. So this must be imported in your model (using System.ComponentModel.DataAnnotations)

System.ComponentModel.DataAnnotations contain various attributes that can be applied on a model field. Along with that it has all necessary validators (like, Required, Range, MaxLength, MinLength, Regular Expression, Custom validator, etc).

For our case, we should write - 

[Required(ErrorMessage="Please Enter Person Name!")]
[Display(Name="Person Name")]
public string PersonName { get; set; }

This will automatically handle required validation for Person Name field input.
Now, in the view (.aspx, or .cshtml), we need to put ValidationSummary in order to display error message in case validation fails.
@Html.ValidationSummary(false, "Please correct following errors and try again!")

The last thing is to add a condition in HttpPost method to relaunch the view with latest inputs and error messages, in case if validation(s) fail.

[HttpPost]
        public ActionResult PersonEdit(Person person)
        {
            if (ModelState.IsValid == false)
            {
                return View("PersonEdit",  person);
            }
            else
            {
             //Write code to define actions on success
            }            
        }

Now, when the view is launched with person model, it will have same inputs as well as validation errors, so that they will get displayed in ValidationSummary control in view to let users know about the errors.

NOTE: Also, remember to put @Html.ValidationSummary control before @Html.BeginForm block, otherwise it will always show you validation messages even before HttpPost.

1 comment:

  1. It was really a nice post and I was really impressed by reading this .NET Online Course

    ReplyDelete

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman

Blog Archive