Monday, May 12, 2014

Client Side Validation in ASP .NET MVC using Data Annotation Attributes

Client Side Validation in ASP .NET MVC using Data Annotation Attributes

In this post we will know how to apply client side validation in Asp .Net MVC.
Step : 1 Take a New ASP.NET MVC 4 Web Application
  Now, you will have a structure

Step : 2 Add a class in the Models folder and write the property which you want to show in view.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.ComponentModel.DataAnnotations;
namespace ValidateMvcForm.Models
{
    public class User
    {
        [Required]
        [StringLength(30)]
        public string FirstName { get; set; }
         
        [StringLength(30)]
        public string MiddleName { get; set; }
        [Required]
        [StringLength(30)]
        public string LastName { get; set;}
        [RegularExpression(@"([a-zA-Z0-9][-a-zA-Z0-9_\+\.]*[a-zA-Z0-9])@([a-zA-Z0-9][-a-zA-Z0-9\.]*[a-zA-Z0-9]\.(arpa|root|aero|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|([0-9]{1,3}\.{3}[0-9]{1,3}))")]
        public string EmailAddress { get; set; }
         
    }
}
Step : 3 Now, Add a Controller in the Controller folder, by right click on Controller (folder) --> Add --> Controller and add an Action in this Controller
?
1
2
3
4
public ActionResult Registration()
        {
            return View();
        }
Now, right click on View() and add a View



and add the following code in Controller as well
[HttpPost]
        public ActionResult Registration(Models.User user)
        {
            return View();
        }
Step : 4 In Registration.cshmtl, write the following code


Now, build your application and run.
And when we click on "Submit" button it looks like

So, Form will not post until we don't fill form according to our model.
So, basically for client Side Validation we just need to add the following code
@section scripts{
@Scripts.Render("~/bundles/jqueryval")
}
and add Attributes in Model class.

No comments :

Post a Comment