In my previous article we learned how to do validation in ASP.NET Web from using Validation Control as well as DataAnnotations attributes.
You can read that article here: Validation In ASP.NET Web Form.
You can read that article here: Validation In ASP.NET Web Form.
Now we will do the same thing here in ASP.NET MVC Application.
Step 1: Create new ASP.NET Web Application, select MVC template and click 'Ok'.


It will create Model, View and Controller folders in project.

Step 2: Now let's create a Model class first, for that right click on Models folder, click Add, then Class and give a name 'UserRegistration.cs'.

Step 3: Now let us create property for the following fields and implement validation for the field.
For that add the following code in your model class file. Remember these are the same things we have done in 'Class Library' in my previous article.
- public class UserRegistration
- {
- [Required(ErrorMessage = "Name is required")]
- public string name
- {
- get;
- set;
- }
- [Required(ErrorMessage = "email is required")]
- [RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$", ErrorMessage = "Invalid email format.")]
- public string email
- {
- get;
- set;
- } = "";
- [Required(ErrorMessage = "Mobile is required")]
- [RegularExpression(@"\d{10}", ErrorMessage = "Please enter 10 digit Mobile No.")]
- public string mobile
- {
- get;
- set;
- }
- [Required(ErrorMessage = "Password is required")]
- [DataType(DataType.Password)]
- public string Password
- {
- get;
- set;
- }
- [Required(ErrorMessage = "Confirm Password is required")]
- [DataType(DataType.Password)]
- [Compare("Password")]
- public string ConfirmPassword
- {
- get;
- set;
- }
- [Required(ErrorMessage = "Age is required")]
- [Range(typeof(int), "18", "40", ErrorMessage = "Age can only be between 18 and 40")]
- public string age
- {
- get;
- set;
- }
- }


sreenivasa kPosted Jan 10, 2016, 12:29 PM
very nice
Santhakumar MunuswamyPosted Jan 10, 2016, 11:30 AM
Thanks for nice article
Karthikeyan KPosted Jan 10, 2016, 9:47 AM
Good one sir...
Ankur MistryPosted Jan 10, 2016, 9:28 AM
Thank you
Humayun Kabir MamunPosted Jan 10, 2016, 8:54 AM
Nice...
Ankur MistryPosted Jan 10, 2016, 4:39 AM
Thank you Ankit Bansal
Ankit BansalPosted Jan 10, 2016, 2:46 AM
nice one..keep sharing..