Search code examples
jqueryvalidationasp.net-mvc-3html-helper

JQuery Validation not working correctly with MVC 3


The issue I'm having with jquery validation is that it doesn't like a dot notation in names. I'm using the Microsoft HTML helpers that automatically create a name based on the view model and the name of the field. So, for instance, the MS Html handler would generate "AuditDoc.Title" from an html textbox with the variable "Title" within the "AuditDoc" viewmodel. My dilemma is that JQuery validation doesn't like that DOT in the middle of the name. So when I put "AuditDoc.Title" as the name to validate against, it gives me a javascript error. Any way around this? I'd appreciate the help!

        $("#SaveCreateInProgress").click(function () {
        $("#AdvanceDirection").val("SAVE");
        $("#CreateInProgressMainForm").validate({
            rules: {
                AuditDoc.Title: "required",
                AuditDoc.ActivityId: "required"
            },
            messages: {
                AuditDoc.Title: "Please enter a Title (JQuery Validate)",
                AuditDoc.ActivityId: "Please select an Activity Id (JQuery Validate)"
            },
            submitHandler: function (form) {
                alert("Submitted!");
            }
        });

Solution

  • try putting the quotes like

    $("#SaveCreateInProgress").click(function () {
            $("#AdvanceDirection").val("SAVE");
            $("#CreateInProgressMainForm").validate({
                rules: {
                    "AuditDoc.Title": "required",
                    "AuditDoc.ActivityId": "required"
                },
                messages: {
                    "AuditDoc.Title": "Please enter a Title (JQuery Validate)",
                    "AuditDoc.ActivityId": "Please select an Activity Id (JQuery Validate)"
                },
                submitHandler: function (form) {
                    alert("Submitted!");
                }
            });
    

    PS why dont you use the unobtrusive validation that come with the MVC

    edit

    here is the demo http://jsfiddle.net/DWHjw/