Wednesday, June 6, 2012

Validation for MVC ASP.net Razor view

I got stuck with creating the validation for the MVC project and I couldn't find many resources.

There are three steps needed to implement validation in the MVC project:
1. Attribute on the variables
2. HTTP helpers Validation summery and messages on the view
3. Javascript  and Jquery libraries

Here is how you implement the validation
1.Attribute on the variables
They are placed on top of the variables stating the limitations on the variables (e.g. has to be a number, too long or short, can't be null..etc).
Here is an example that I used for a variable that can not be over 1024 and is also required.
        [Required(ErrorMessage="Value is Required")]
        [Display(Name="DialogueSubject")]
        [StringLength(maximumLength: 1024, ErrorMessage = "too long")]
        public string DialogueSubject { get; set; }

make sure you include using System.ComponentModel.DataAnnotations;

2.HTTP helpers Validation summery and messages on the view
These lines would fire up once a validation error shows up.
At the top of the form I placed the following
    @Html.ValidationSummary(true, "Error. See the notification below")
and after each one of the textboxes I placed this line. It would get the error from the attribute and tell the user which rule was violated.
    @Html.ValidationMessageFor(m => m.DialogueSubject)

3.Javascript  and Jquery libraries
And this was the part that I was stuck on. I didn't include the Jquery libraries. These are the 2 libraries that need to be included:
    jquery.validate.unobtrusive.min.js
    jquery.validate.min.js

This is what the final result would look like:

And that is it! happy validation