Executing validation with jquery.validate

I'm trying to learn / understand client-side validation with jquery.validate. Currently, I have a basic form defined as shown here:

<form id="myform">
  <input id="firstNameTextBox" type="text" />
  <input id="lastNameTextBox" type="text" />
  <input type="button" value="Test" onclick="return testButtonClick();" />
</form>

<script type="text/javascript">
    $(document).ready(function () {
        $("#addPersonForm").validate({
            rules: {
                firstNameTextBox: "required",
                lastNameTextBox: "required"
            },
            messages: {
                firstNameTextBox: "Please enter the first name.",
                lastNameTextBox: "Please enter the last name."
            }
        });
    });

    function testButtonClick() {
      string errorMessage = validateFormAndGetMessage();
      alert(errorMessage); 
      return false;
    }
</script>

When someone clicks the "Test" button, I want to determine if the form is valid. If it is invalid, I want to display the message associated with the offending rule. How do I do this?

Answers


You can call form() on the validator, see http://docs.jquery.com/Plugins/Validation/Validator/form

So you will need to update your code to store the validator, also, you should use the jquery event wireup to capture the click on the button:

<form id="myform">
  <input id="firstNameTextBox" type="text" />
  <input id="lastNameTextBox" type="text" />
  <input type="button" value="Test" id="testbutton" />
</form>

<script type="text/javascript">
$(document).ready(function () {
    validator = $("#addPersonForm").validate({
        rules: {
            firstNameTextBox: "required",
            lastNameTextBox: "required"
        },
        messages: {
            firstNameTextBox: "Please enter the first name.",
            lastNameTextBox: "Please enter the last name."
        }
    });

    $('#testbutton').click(function(event) {
        event.preventDefault();
        validator.form(); //This will show the validation messages on the form      
    });
});
</script>

Need Your Help

Declare variable in a Play2 scala template

html scala templates playframework playframework-2.0

How do you declare and initialize a variable to be used locally in a Play2 Scala template?

Java toString Issue

java arrays list generics tostring

I am having an issue with the toString method in Java. Here's the run down... I have a database that I am querying. The query returns all of the members in the database, and I'd like to return these