Validation
To implement validation in ASP.NET MVC, you should use DataAnnotation attributes. These attributes are present in System.ComponentModel.DataAnnotations namespace. Validation attributes specifies the behaviour, which you want apply to the properties of models. ASP.NET MVC framework automatically enforces validation rules and display validation messages in View.
- Required- This indicates that the property is a required field.
- StringLength- This defines a maximum length for the string field.
- MaxLength- This specifies maximum length for the string field.
- MinLength- This specifies minimum length for the string field.
- Range- This defines a maximum and minimum value for the numeric field.
- RegularExpression- This specifies that the field value must match with the specified Regular Expression.
- CreditCard- This specifies that the specified field is a credit card number.
- EmailAddress- This validates with an Email address format.
- FileExtension- This validates with the file extension.
- Phone- This specifies that the field is a phone number, using regular expression for the phone numbers.
- CustomValidation- This specifies custom validation method to validate the field.
Now, the sample is given below.
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
- using System.Web.Mvc;
- public class EmployeeModel {
- 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;
- }
- }
- }

Rajan KumarPosted Mar 25, 2022, 9:00 AM
Nice article
Richa YadavPosted Jun 1, 2017, 7:02 AM
Thanks... Keep posting...
Former memberPosted May 30, 2017, 6:55 AM
Please tell me how to validate Credit Card and phone no using built-in annotation.