MVC 2 jQuery Client-side Validation
Well, I watched Phil Haack’s show What's New in Microsoft ASP.NET MVC 2 and was impressed about the client-side validation (starts at 17:45) that MVC 2 offers.
I tried creating the same, but Phil does not show what .js files need to be included and also I was not able to find the source code for the application that he used. In order to find out the required JavaScript file references, I added all of the files in my application to the page and ran it. Of course it worked, but this is definitely not an optimum solution.
By removing one at a time and testing the app, I’ve short-listed the following ones:
1: <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script2: <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>3: <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
Now, a little about the feature itself. Say, I’m working with a Book application so my model will look something like:
1: public class Book
2: {
3: [HiddenInput(DisplayValue = false)]
4: public int BookId { get; set; }
5:
6: [DisplayName("Book Title")]
7: [Required(ErrorMessage = "Book title is required")]
8: [StringLength(20, ErrorMessage = "Must be under 20 characters")]
9: public string Title { get; set; }
10:
11: [Required(ErrorMessage = "Author is required")]
12: [StringLength(40, ErrorMessage = "Must be under 40 characters")]
13: public string Author { get; set; }
14:
15: public decimal Price { get; set; }
16:
17: [DisplayName("ISBN")]
18: [StringLength(13, ErrorMessage = "Must be 13 characters")]
19: public string Isbn { get; set; }
20: }
This ensures that the data passed will be validated upon post. But what would happen if you add the line (along with the above mentioned .js files):
1: <% Html.EnableClientValidation(); %>
Now, this acts as ‘on-the-fly’ or ‘real-time’ validation. Now, when the user types 20 characters for the Title, the error shows up right on the 21st character. Beautiful… and you do not have to create the JavaScript function(s) for this. They’re auto-magically created for you. (Doing a ‘View Source’ on the browser page shows you the JavaScript logic that goes on behind the scenes).
I bumped into another post that shows how .net 4 allows us to create custom validation attributes: Dynamic Range validation in MVC 2. This will help us attach virtually any business logic to the model itself.
Please see the source code I’ve worked with.