Brainchild
Brainchild

Reputation: 1874

validating user input inside modal popup using jquery validation plugin

I am trying to validate user input in a jquery UI modal dialog. Jquery validation plugin is used for validation.

trying to verify validation in popup button click

<form id="frm">
    <div>
        <button name="btn" id="btn" type="button" >OpneModal</button>
    <div id="dlg" style="display:none">
        <div>
            Name: <input type="text" id="txtName" name="txtName"/>
        </div>
        <div>
        </div>
        </div>
        </div>
    </form>


 $(
     function () {
           var rules = {
            txtName: {
                required: true
            }
        };
        var messages = {
            txtName: {
                required: "Please enter name"
            }
        };
       $("#frm").validate({rules:rules, messages:messages});


          $("#btn").click(
              function () {

                  $("#dlg").dialog(
                      {
                          modal: true,
                          buttons: {
                              "Save": function () {
                                alert(  $("#frm").valid());
                              },
                              "Cancel": function () {
                                  $("#dlg").dialog("close");
              }
                          }

                      }
                      );
              }
              );

      });

But the validation is always success.

code is in js fiddle: http://jsfiddle.net/aGJrZ/6/

Upvotes: 2

Views: 27970

Answers (1)

Sparky
Sparky

Reputation: 98738

The jQuery Validation plugin requires that all input elements must be contained within a set of <form></form> tags. However, using the DOM inspector, you can see that when your dialog box is constructed, it is outside of the <form></form> entirely.

Re-factor the HTML so that the form is contained inside your dialog...

<button name="btn" id="btn" type="button">Open Modal</button>
<div id="dlg" style="display:none">
    <form id="frm">
        <div>
            Name:  <input type="text" id="txtName" name="txtName" />
        </div>
    </form>
</div>

DEMO: http://jsfiddle.net/aGJrZ/9/

Upvotes: 1

Related Questions