In previous article I’ve show you how to validate form using jQuery validation plugin and view model Data Annotations. With MVC 3 Microsoft have implemented jQuery validation referring to standard Data Annotation attributes. Let me show you how to use it in simple example.
First of all in new solution in web.config file by default you can find 2 parameters:
<appSettings> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings>
Specify view model with Data Annotations
using System; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using OPC.Models.Helpers; namespace OPC.Models.DAL { [MetadataType(typeof(User_Validation))] public partial class User { } [Bind(Exclude="Id")] public class User_Validation { [Required(ErrorMessage="Required field")] [StringLength(40, ErrorMessage="Max 40 chars")] public string Login { get; set; } [Required(ErrorMessage=" Required field ")] [DataType(DataType.Password)] [StringLength(20, ErrorMessage=" Max 20 chars ")] public string Password { get; set; } [Required(ErrorMessage=" Required field ")] public int OfficerId { get; set; } } }
Now we need to create view which inherits our view model.
By selecting “Reference Script Libraries” checkbox references to JavaScripts will added to the view:
Instead I prefer put references in master layout at the bottom of the page:
And that’s it, we done. As the result we have client side validation with jQuery plugin.
If you look at the HTML code, you will see how model data annotation transformed info HTML tag parameters for jQuery validation plugin.
Sources and useful info:
Comments
Hi,
First of all Thanks for the excellent blog. i am reading it for MVC Stuff. i have a small doubt on this validation part. i am using data annatations like you mentioned. But when i am validating by
var isValid = $("form").valid();
alert(isValid);
with out collecting response from Remote method. it displays result. i found it put a debugger on remote method and find result in alert box. The method execution is not completed but alert message as True; I need to submitt after remote metod validation only.
How to Resolve it?
Hi i have a jquery call for getting Id to a action method for the same action method i have Required Feild Validator
so if i click i am getting id but the ModelState.IsValid is returning False but the Validator is true Can Some body help me out in this
Join the discussion