Validation in ASP.NET MVC
- Validation uses built-in attribute of ASP.NET called DataAnnotations and is used to validate inputs provided by the user.
- Validation is a very powerful attribute of ASP.NET MVC and it can be applied to entire model class or any property of model class.
- It places a restriction on the inputted data by the user, and if the data doesn't follow the specified rules then it will generate an Error Message and won't allow the user to submit form.
- It's really helpful from development point of view, as the developer always gets the data in single specified format, thus can easily handle it.
- Following table shows few of the most commonly used Validations in ASP.NET MVC:
|Validation in ASP.NET MVC|
|1||Range||Value sould lie b/w specified range (e.g. Age)|
|2||StringLength||Maximum Characters (e.g. First Name)|
|3||Required||This field is Compulsory. (*required)|
|4||RegularExpression||The user input must match the provided format (e.g. Date / Time)|
|5||MaxLength||Sets the Maximum Limit.|
|6||CreditCard||For Credit Card details.|
|7||CustomValidation||Custom validations defined by developer.|
|8||FileExtension||Restriction on File Extension (e.g. only img file)|
|9||MinLength||Sets the Minimum Limit.|
|10||EmailAddress||Email Address must be provided.|
|11||Phone||Phone Number Format must followed.|
- I hope you have now got the basic idea of what is validation.
- Now let's implement one of these validations in ASP.NET MVC.
- So, open your StudentModel.cs file, it's our model class which we have created in tutorial: How to Create a New Model in ASP.NET MVC.
- You can see in the above figure that I have added an attribute before Name variable.
- It's a StringLength Validation and the first parameter which I have set to 20 is the maximum length of string allowed.
- While minimum length is specified as 4, so this Validation is restricting the Name model to only accept value of length between 4 and 20.
- So, now run your application and check the View and in Name Text box enter your name, here are the results:
- In Case 1, the input string length is less than 4, while in Case 2, length is greater than 20.
- That's why it has given error in both cases.
- We can also add multiple Validation to single property, as shown in below figure:
- Below this StringLength, I have placed another Validation in ASP.NET MVC which is [Required].
- So, now it will also make sure that Name field is not empty.
- Here's the video demonstration of Validation in ASP.NET MVC, have a look at it: