Data validation is a key aspect for developing web application. In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace and are availlable to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework orm models.
Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.
Validation attributes comes from System.ComponentModel.DataAnnotations. -
Available validation attributes are-
System.ComponentModel.DataAnnotations.CompareAttribute
System.ComponentModel.DataAnnotations.CustomValidationAttribute
System.ComponentModel.DataAnnotations.DatatypeAttribute
System.ComponentModel.DataAnnotations.MaxLengthAttribue
System.ComponentModel.DataAnnotations.MinLengthAttribute
System.ComponentModel.DataAnnotations.RangeAttribute
System.ComponentModel.DataAnnotations.RegularExpressionAttribute
System.ComponentModel.DataAnnotations.RequiredAttribute
System.ComponentModel.DataAnnotations.StringLengthAttribute
System.Web.Security.MembershipPasswordAttribute
Data Annotation Validator Attributes are :-
01. DataType
Specify the datatype of a property
02. DisplayName
specify the display name for a property.
0.3 DisplayFormat
specify the display format for a property like different format for Date proerty.
04. Required
Specify a property as required.
05. ReqularExpression
validate the value of a property by specified regular expression pattern.
06. Range
validate the value of a property with in a specified range of values.
07. StringLength
specify min and max length for a string property.
08. MaxLength
specify max length for a string property.
09. Bind
specify fields to include or exclude when adding parameter or form values to model properties.
10. ScaffoldColumn
specify fields for hiding from editor forms.
Example :-
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
- using System.Web.Mvc;
- namespace Employee.Models
- {
- [Bind(Exclude = "EmpId")]
- public class Employee
- {
- [ScaffoldColumn(false)]
- public int EmpId { get; set; }
- [DisplayName("Employee Name")]
- [Required(ErrorMessage = "Employee Name is required")]
- [StringLength(100,MinimumLength=3)]
- public String EmpName { get; set; }
- [Required(ErrorMessage = "Employee Address is required")]
- [StringLength(300)]
- public string Address { get; set; }
- [Required(ErrorMessage = "Salary is required")]
- [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
- public int Salary{ get; set; }
- [Required(ErrorMessage = "Please enter your email address")]
- [DataType(DataType.EmailAddress)]
- [Display(Name = "Email address")]
- [MaxLength(50)]
- [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
- public string Email { get; set; }
- }
- }
- <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
- <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Presenting the model in the view
- @model Employee.Models
- @{
- ViewBag.Title = "Employee Details";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- @using (Html.BeginForm())
- {
- <div class="editor-label">
- @Html.LabelFor(m => m.EmpName)
- </div>
- <div class="editor-field">
- @Html.TextBoxFor(m => m.EmpName)
- @Html.ValidationMessageFor(m => m.EmpName)
- </div>
- <div class="editor-label">
- @Html.LabelFor(m => m.Address)
- </div>
- <div class="editor-field">
- @Html.TextBoxFor(m => m.Address)
- @Html.ValidationMessageFor(m => m.Address)
- </div>
- <div class="editor-label">
- @Html.LabelFor(m => m.Salary)
- </div>
- <div class="editor-field">
- @Html.TextBoxFor(m => m.Salary)
- @Html.ValidationMessageFor(m => m.Salary)
- </div>
- <div class="editor-label">
- @Html.LabelFor(m => m.Email)
- </div>
- <div class="editor-field">
- @Html.TextBoxFor(m => m.Email)
- @Html.ValidationMessageFor(m => m.Email)
- </div>
- <p> <input type="submit" value="Save" />
- </p>
- }
Some more example :-[Required(ErrorMessage="FirstName Required:")][DisplayName("First Name:")][RegularExpression(@"^[a-zA-Z'.\s]{1,40}$",ErrorMessage="Special Characters not allowed")][StringLength(50, ErrorMessage = "Less than 50 characters")]public string FirstName { get; set; }[Required(ErrorMessage="LastName Required:")][RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage = "Special Characters not allowed")][DisplayName("Last Name:")][StringLength(50, ErrorMessage = "Less than 50 characters")]public string LastName { get; set; }[Required(ErrorMessage="EmailId Required:")][DisplayName("Email Id:")][RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email Format is wrong")][StringLength(50, ErrorMessage = "Less than 50 characters")]public string EmailId { get; set; }[Required(ErrorMessage="Password Required:")][DataType(DataType.Password)][DisplayName("Password:")][StringLength(30, ErrorMessage = "Less than 30 characters")]public string Password { get; set; }[Required(ErrorMessage="Confirm Password Required:")][DataType(DataType.Password)][Compare("Password", ErrorMessage = "Confirm not matched.")][Display(Name = "Confirm password:")][StringLength(30, ErrorMessage = "Less than 30 characters")]public string ConfirmPassword { get; set; }[Required(ErrorMessage="Street Address Required")][DisplayName("Street Address1:")][StringLength(100, ErrorMessage = "Less than 100 characters")]public string StreetAdd1 { get; set; }[DisplayName("Street Address2:")][StringLength(100, ErrorMessage = "Less than 100 characters")]public string StreetAdd2 { get; set; }[Required(ErrorMessage="City Required")][DisplayName("City:")][RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage = "Special Characters not allowed")][StringLength(50, ErrorMessage = "Less than 50 characters")]public string City { get; set; }[Required(ErrorMessage="State Required")][DisplayName("State:")][RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage = "Special Characters not allowed")][StringLength(50, ErrorMessage = "Less than 50 characters")]public string State { get; set; }[Required(ErrorMessage="ZipCode Required")][DisplayName("Zip Code:")][StringLength(20, ErrorMessage = "Less than 20 characters")]public string Zip { get; set; }[Required(ErrorMessage = "Enter Verification Code")][DisplayName("Verification Code:")]public string Captcha { get; set; }
No comments:
Post a Comment