Showing posts with label Validate Page. Show all posts
Showing posts with label Validate Page. Show all posts

Saturday, April 21, 2012

Implement Custom Validation in ASP.NET MVC

This article aims to explain how we can implement Custom validation (server-side) in ASP.NET MVC.

System.ComponentModel.DataAnnotations namespace provides set of predefined validations which are common in almost all scenarios (like, Required, Range, Regular Expression, etc). Click here for more information.

This namespace contains "ValidationAttribute" class which is a base class for all validation attributes.
Following are the steps to be performed in order to implement a custom validation.
1. Inherit a new validation class from ValidationAttribute base class. (A new class can be created anywhere but should have System.Component.DataAnnotations referenced.)
2. Override "IsValid" method and write our own validation. (Here, we can get the value entered by user for the corresponding field/ property, so we can validate it).
3. Apply new attribute on the field/ property of a model wherever you need that custom validation to fire.

Sample Code:
In our "Person" model, we have a "BirthDate" field. We now want to validate if the Age of a person must be 18  or above.
1. A class inherited from ValidationAttribute, and overriding of IsValid method within:



[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class BirthDateValidation : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (Convert.ToDateTime(value) >= DateTime.Now.AddYears(-18))
            {
                return false;
            }
            return true;
        }
    }


2. Applying "BirthDateValidation" attribute on Birthdate property.


[Display(Name="Birth Date")]
        [BirthDateValidation(ErrorMessage="Registration is only allowed for people above 18 years.")]
        public DateTime BirthDate { get; set; }


3. Last thing, as it is a server-side validation (just like, Required, Range, etc), dont forget to relaunch the view from corresponding HttpPost action in your controller, in case if ModelState.IsValid is False. (indicating, a validation failed)

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


That's all we need to implement this validation:

Screenshot:


Wednesday, April 11, 2012

How to validate a page using Java script

Lets consider a following scenario:

There is a web page which has many input control, and validators (required field validator, custom validator, etc).

Now, there is a link button which already has some javascript written for its "onclientclick" event.
So, generally when this button is clicked:
a. First,it will execute java scripts written in onClientClick
b. page-level validations (i.e. required field validators, etc) will be performed
c. if page-level validations are passed, server-side validations will be performed
d. if server-side validations are passed, server-side Click event will be executed.

So, even if the inputs are invalid, it will always execute, onClientClick.

But there are certain cases when you need your main code of OnClientClick javascript to be executed only if the page is valid.
In such cases, you can add a code to validate page in your onClientClick method, and to allow execution of further code only if page is valid. For that, we can use "Page_ClientValidate" and "Page_IsValid".

Write following java script in "onclientclick" event of that link button in order to achieve this -


OnClientClick = "if(typeof(Page_ClientValidate) == 'function')
{ Page_ClientValidate(); if (Page_IsValid == true) { JavaScriptFunctionForTargettedAction(); } } return false;"/>


Here JavaScriptFunctionForTargettedAction() is the javascript code/ method you have originally intended to execute in onclientclick evnet