Reputation: 6689
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?
Upvotes: 1
Views: 123
Reputation: 34193
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>
Upvotes: 1