This article explains the ASP.NET MVC server-side validation using the Data Annotation classes. ASP.NET MVC Framework validates the data passed to the controller action and it populate ModelState with validation state based on the success/failure. Then the Model State passed object to the controller for the further process. Server side validations are play important role with sensitive information of a user.

Server Side Model Validation

  • Server side validations are required for ensuring that the received data is correct and in-valid.
  • If the received data is valid,then it will continue with further processing else show the Error message

Why we go for server-side Validation :

Some user may disable script in his browser, In this scenerio we must require to validate our data from dirty input values from the user. To avoid this we can use sever-side validation. we can validate a “MODEL”  in server-side by two ways:

  •     Model Validation with Data Annotations
  •     Explicit Model Validation

We already discussed about Model validation using Data Annotation here, so  let we discuss Explicit validation using simple registration form with user input.

Model :

Controller :

Note :

ModelState: Gets the model state dictionary object that contains the state of the model. As per below, we can see that input values listed in the model-state.

ExplictValidationController

Index :

Explanation:

while pressing the submit button, it will post the data. If input data is not valid then it will add error to model-state using AddModelError() using ModelStateDictionary class

Output :

 Sever side validation using model in mvc - dotnet-helper

After pressing the submit button, it will post the data.If input data is not valid then it will show the error msg using @Html.ValidationMessageFor

Sever side validation using model mvc - dotnet-helper

Here , In controller i am using  if (Request.HttpMethod == “POST”) instead of checking ispostback. Using this we can use same action method for loading and validating using Html.BeginForm()