How to apply Server side validation in ASP.NET MVC?

Server side validations are very important before playing with sensitive information of a user. Server-side validation must be done whether we validate the received data on the client side. User could disable script in his browser or do something else to bypass client-side validation. In this case server-side validation must require to protect our data from dirty input.
In ASP.NET MVC, there are two ways to validate a model on server side:

  1. Explicit Model Validation – This is the traditional way to validate the model data by using IF..Else..IF statement. In this way, you need to check your model property values one by one for your desired result. If model property values are unexpected, inject error messages within ModelState.
    class HomeController : Controller
    {
    	[HttpPost]
    	public ActionResult ExplicitServer(UserViewModel model)
    	{ //Write custom logic to validate UserViewModel
    		if (string.IsNullOrEmpty(model.UserName))
    		{
    			ModelState.AddModelError("UserName", "Please enter your name");
    		}
    		if (!string.IsNullOrEmpty(model.UserName))
    		{
    			Regex emailRegex = new Regex(".+@.+\\..+");
    			if (!emailRegex.IsMatch(model.UserName))
    				ModelState.AddModelError("UserName", "Please enter correct email address");
    		}
    		if (ModelState.IsValid) //Check model state
    		{
    			//TO DO:
    		}
    	}
    }
  2. Model Validation with Data Annotations – Data Annotations was introduced with .NET 3.5 SP1. It has a set of attributes and classes defined in the System.ComponentModel.DataAnnotations assembly. Data Annotations allow us to decorate model classes with metadata. This metadata describes a set of rules that are used to validate a property.
    public class UserViewModel
    {
    	[Required(ErrorMessage = "Please Enter Email Address")]
    	[RegularExpression(".+@.+\\..+", ErrorMessage = "Please Enter Correct Email Address")]
    	public string UserName
    	{
    		get;
    		set;
    	}
    	[Required(ErrorMessage = "Please Enter Password")]
    	[StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    	public string Password
    	{
    		get;
    		set;
    	}
    }
Tagged , . Bookmark the permalink.

One Response to How to apply Server side validation in ASP.NET MVC?

  1. Ganesh Mandlik says:

    Great Explanation!!!!!!
    Thank you sir!!!!!!!!!!!!!!!!!!!!!!

Leave a Reply