Validation in MVC

validation mvc

Validation in ASP.NET MVC

In all web applications reality is that users will enter data that isn’t valid and cannot be used. Model validation is the process by which we can ensure that data received by the application is suitable for binding to a model. When this is not the case it provides user useful information that will help explain the problem.

MVC Framework provides extensive support for the validation. In this ASP.NET MVC tutorial we are going to see following topics about validation in MVC.

  • Creating Example App
  • Explicite vaidation in action method
  • Display validation message
  • Validaton using metadata in model class
  • Defining Self Validating Models
  • Client side validation

Creating Example App :

Create a new web application in visual studio using Empty Template and checking the option to add core references and folders for MVC.
Add a new file Examination.cs in the Models folder having following content.

Add a controller named HomeController having following content :

I will need a simple layout for some of the examples in this tutorial. I created the Views/Shared folder and added the _Layout.cshtml file to it, the contents of which you can see as following :

Add a new file _ViewStart.cshtml to the Views folder so that layout can be applied automatically.

Contents of ViewStart.cshtml file :

To complete the preparation, I created two views to support the action methods, both of which are located in the /Views/Home folder. In following code, you can see the contents of the MakeBooking.cshtml file, which contains a form that allows the user to create a new examination.

When the form is posted back to the application, the MakeBooking action method displays the details of the examination that the user has created using the Completed.cshtml view.

Contents of Completed.cshtml :

whe you run the app and navigate to /Home/MakeBooking URL you will see the following output.

using exmple app 1

using exmple app 2

Explicite validation in action method in MVC :

In explicite validation we validate the model in action method of the controller as shown in following code :

In above code we check the name property is for null. If name is null we use AddModelError method of the ModelState object to generate error.

For Date field we check for the valid Date using ModelState.IsValidField method and check whether date is in future.

If Date is invalid we add generate error using AddModelError method of ModelState object.

Similerly we check the TermsAccepted for valid value which is true.

Finally, we check that the Model proeprties are valid or not using ModelState.IsValid property.

If Form data is valid redirect to completed view otherwise display the errors in makebooking.cshtml view.

Displaying validation errors to users :

Templeted helpers which I used to generate input elements in MakeBooking.cshtml view check the view model for validation errors.

The helpers add a CSS class called input-validation-error to the input elements if an error has been reported for the corresponding properties, which is why I added these CSS styles to the layout when I created the example project:

You can test the explicit validation approach by starting the application, navigating to the /Home/MakeBooking URL, and clicking the Make Booking button without entering any data in the form. The result is shown in Figure :

errors result highlighted elements

The classes that the templated helper methods apply to input elements indicate that there are problems with a field, but they do not tell the user what the problem is.

Fortunately, there are some convenient helper methods that assist in doing this. following code shows one of these helper methods, which I have applied to the MakeBooking.cshtml view.

The Html.ValidationSummary helper adds a summary of the validation errors to the user. If there are no errors, then the helper doesn’t generate any HTML.

displaying validation summary

Useful Overloads of the ValidationSummary Helper Method :

Overloaded Method Description
Html.ValidationSummary() Generates a summary for all validation errors
Html.ValidationSummary(bool) If the bool parameter is true, then only model-level errors are displayed (see the explanation after the table). If the parameter is false, then all errors are shown.
Html.ValidationSummary(string) Displays a message (contained in the string parameter) before a summary of all the validation errors
Html.ValidationSummary(bool, string) Displays a message before the validation errors. If the bool parameter is true, only model-level errors will be shown.

By contrast, model-level errors can be used when there is some problem arising from an interaction between two or more property values.

As a simple example, let’s imagine that customers named Joe cannot make appointments on Mondays. Following code shows how I can enforce this rule with an explicit validation check in the MakeBooking action method and report problems as model-level validation errors.

I can then update the MakeBooking.cshtml view file to use the version of the ValidationSummary helper method that takes a bool parameter to display only the model-level errors, as shown :

You can see the result of these changes in Figure where I have entered the name Joe and specified a date, which is a Monday.

displaying validation summary model level errors

You can see from the figure that there are two validation errors. The first is the model-level error that arises from Joe trying to get a Monday appointment. The second is that the terms and conditions check box is unchecked.

Since I am displaying only model-level errors in the validation summary, the user will not see any information about the second problem in the summary, something I will address in the next section.

Displaying Property-Level Validation Messages :

The reason you might want to restrict the validation summary to model-level errors is to display property-level errors alongside the fields themselves, in which case you will not want to duplicate the property-specific messages.

Following code shows how I updated the MakeBooking.cshtml view to display model-level errors in the summary and to display property-level errors alongside the corresponding input field.

The Html.ValidationMessageFor helper displays validation errors for a single model property. You can see the effect it has on the MakeBooking view in Figure :

using per property validation message helper

The helper only inserts HTML into the response if there is a validation error for the property it is applied to and generates elements like this:

The class that the elements are assigned to corresponds to the one of the styles that I defined in the _Layout.cshtml file:

Specifying validation rules using metadata :

The MVC Framework supports the use of metadata to express model validation rules. The advantage of using metadata is that the validation rules are enforced anywhere that the binding process is applied throughout the application, not just in a single action method. The validation attributes are detected and enforced by the built-in default model binder class, DefaultModelBinder.

Validation rules in examination.cs file :

Creating a Custom Property Validation Attribute :

Validation isn’t limited to just the built-in attributes. I can also create my own by deriving from the ValidationAttribute class and implementing custom validation logic.

This is a lot more useful and to demonstrate how this works, I have added an Infrastructure folder to the example project and created a class file called MustBeTrueAttribute.cs within it. Following code shows the contents of the new class file.

Applying a Custom Validation Attribute in the Examination.cs File :

You can see the effect of custom validation attribute when you run the application and click make booking button without checking the termsconditions chekcbox.

Deriving from the Built-In Validation Attributes :

In the previous example, I built a validation attribute from scratch, but I can also derive new classes from the built-in attributes, which gives me the ability to extend their behavior. In following code, you can see the contents of a new class file called FutureDateAttribute.cs that I added to the Infrastructure folder.

Applying a Custom Model Validation Attribute in the Appointment.cs File :

Creating a model validation attribute :

The custom validation attributes I have created so far are applied to individual model properties and this means they are only able to raise property-level validation errors.

I can use attributes to validate the entire model as well, which allows me to raise model-level errors. As a demonstration, I have created the NoJoeOnMondaysAttribute.cs class file in the Infrastructure folder.
The contents of the new file are shown in following code :

Applying a Model-Level Custom Validation Attribute in the Examination.cs File :

At this point, I am performing the same kinds of validation in the action method and the validation attributes, which means that the user will see two similar error messages for the same validation problem.

To resolve this, I have removed the explicit validation checks from the MakeBooking action method in the Home controller, as shown in following code, which has the effect of making the validation attributes solely responsible for performing the custom validation checks.

Output :

applying whole model custom validation attribute

Defining self validating model :

In self validating model validation logic is a part of model class. Self validating model implements IValidatableObject class.

Adding self validation in examination.cs file :

One benefit of this approach is that the model- and property-level validation is combined in one place, which means that all of the errors are displayed together, as shown in Figure :

self validating model class effect

Client-Side validation :

The MVC Framework supports unobtrusive client-side validation. The term unobtrusive means that validation rules are expressed using attributes added to the HTML elements that views generate.

These attributes are interpreted by a JavaScript library that is included as part of the MVC Framework that, in turn, configures the jQuery Validation library, which does the actual validation work.

In the following sections, I will show you how the built-in validation support works and demonstrate how I can extend the functionality to provide custom client-side validation.

Client-side validation is controlled by two settings in Web.Config file :

Ensuring that the MVC Framework will generate the attributes required for validation is only part of the setup process. I also have to add the JavaScript packages that process those attributes and check the data that the user has entered into the form.

All of the required packages are available through NuGet, so select Package Manager Console from the Visual Studio Tools ➤ Library Package Manager menu and enter the following commands:
Install-Package jQuery –version 1.10.2

Install-Package jQuery.Validation –version 1.11.1

Install-Package Microsoft.jQuery.Unobtrusive.Validation –version 3.0.0

These packages add files to the Scripts folder, which I then need to add to the layout with script elements, as shown following :
Adding Script Elements for the Validation Libraries to the _Layout.cshtml File :

Validation attributes applied in examination.cs file :

You can see the effect of the client-side validation by starting the application, navigating to the /Home/MakeBooking URL and entering the letter X into the name field.

Hit the tab key or click one of the other input elements and you will immediately see a validation message produced by the JavaScript running in the browser, as shown in Figure :

Remote Validation :

Remote validation is a client-side validation technique that invokes an action method on the server to perform validation.

Adding a Validation Action Method to the HomeController.cs File :

Actions methods that support remote validation must return the JsonResult type, which tells the MVC Framework that I am working with JSON data.

In addition to the result, validation action methods must define a parameter that has the same name as the data field being validated: this is Date for the example.

I make sure that I can parse a DateTime object from the value that the user has submitted and, if I can, check to see that the date is in the future.

I express validation results using the Json method, which creates a JSON-formatted result that the client-side remote validation script can parse and process.

If the value that I am processing meets my requirements, then I pass true as the parameter to the Json method, like this:

If I am unhappy with the value, I pass the validation error message that the user should see as the parameter, like this:

In both cases, I must also pass the JsonRequestBehavior.AllowGet value as a parameter. This is because the MVC Framework disallows GET requests that produce JSON by default, and I have to override this behavior to handle the validation request. Without this additional parameter, the validation request will quietly fail, and no validation errors will be displayed to the client.

Using the Remote Attribute in the Examination.cs File :

You can see how the remote validation works by starting the application, navigating to the /Home/MakeBooking URL, and entering a date that is in the past. As you type, you will see the validation message appear, as shown in Figure :

remote validation mvc

Summary :

  • Use ModelState.IsValid property to check for the valid model.
  • Validation in ASP.NET MVC can be done by following method :
  1. Client-side validation
  2. Self-validating model
  3. Explicite validation in controller action method
  4. Validation in model using metadata
  • You can create your own validation attrbute for custom validation.

Leave a Reply

Your email address will not be published. Required fields are marked *