Jquery validation using Data Annotations ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Monday, 4 April 2016

Jquery validation using Data Annotations

21:32:00 Posted by raviteja swayampu , No comments
How to validate the form data in ASP.NET MVC using Jquery with the help of Data Annotations.
Validating the data is very important before insertion in the database.To validate the developers generally implement three types of validations in the Application development
They are,

1.Client side validation : 

  In client side validation developers validate the data on browser itself (on client side itself)  using       either javascript or javascript frameworks like jquery,Angular js .This code ie executed on browser     and decreases the burdon on server.

2.Server side validation:

  In server side validation developers validate the data on server. The need of server side validations     is: in browsers there is options to stop the execution of the javascritpt. If user set it of then client         side validations won't work and then illegal data may go to database.To prevent this server side           validations are important.

3.Database Validations:

 In this type developers validate the data on server side code using stored procedures. It is optional in  some organizations.But, to get the quality data from user it is better to implement server side  validations.

In this article i am going to explain validations in ASP.NET using data annotations attributes and How to implement client side validations.

Advantage of  using Data Annotation Attributes:

1.They implement both server side and client side validations.
2.Reduces the developers time and effort to write the lot's lines of code for validations
3.Easy to implement.
4.Supports scaffolding.
5.It internally uses Jquery validation plugins (A open source jquery plugin).


Implementing Data Annotations:

Step 1: Create Applications in Visual studio
1.Create a applications in ASP.NET MVC with empty template.(if you don't have internet connection use Basic MVC template.).
2.i had given name "DataAnnotations" for application.

Step 2: Create Model class and apply Annotations
1.Right click Models folder-->Add-->Class-->name it as User.cs
2.Modify the User.cs code with following code (I had given the explanation for code using comments see in the code block below).

Models/User.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//this namespace contains implementations for Data Annotations attributes
using System.ComponentModel.DataAnnotations;
namespace DataAnnotations.Models
{
    public class User
    {
        //primary key
        [Key]
        public int Id { get; set; }

        //It sets custom error Message for the field.
        [Required(ErrorMessage ="Name required")]
        public string Name { get; set; }
        [Required(ErrorMessage ="Email Required")]
        //[DataType(DataType.EmailAddress)]
        //we can use custom Regular expression also to validate data..
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                            @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                            @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                            ErrorMessage = "Email is not valid")]
        public string email { get; set; }

        //"required" attribute is to specify this field is required
        //We can specify custom datatype to the Date field.
        [Required]
        [DataType(DataType.Date,ErrorMessage ="DOB required")]
        public DateTime DOB { get; set; }
        [Required]
        [DataType(DataType.PhoneNumber)]

        //specifies the length of phone number
        [StringLength(10)]
        public long Phone { get; set; }
        [Required]
        public string Address { get; set; }
    }
    //context class for db interactions...
}
Note: check once the javascript validations is enabled in your application or not . check web.config file.if not enable it.
<configuration>
  <appSettings>  
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
</configuration>

Step 3: Add Controller and View
1.Add Controller and name it "HomeController"
2.Add view to the Index action by right clicking-->Add View.
3.Choose "Create template" and "User Model" from drop downs.


4.Click Add to create Create view.
5.By checking  "Reference Script libraries" Visual studio automatically adds the required files to the applications like,


6.Now Run the applications "Press F5".
You will get output like this..

7.Try to give some invalid data into the fields and check the validations...
Dowload the Code from here download

conclusion:
I hope you understand this article thank you i will meet you in another article..


0 comments:

Post a Comment