1

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?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.