i have a form with few fileds and a submit button… when i click on the submit button the form should validate and throw me an error of missing data but whats happening is that, it post the data and than validate the form
what should i do to validate the form and then post the form?
<body>
<form class="cmxform" id="commentForm" method="post" action="">
<div class="subColumns paragraph">
<div class="lefty">
<div class="fontWeight7">
<label for="first_name">
First Name:</label>
<input id="first_name" class="text required" maxlength="200"
name="first_name" />
</div>
</div>
<div class="cdc-left">
<div class="fontWeight7">
<label for="last_initial">
Last Initial:</label>
<input id="last_initial" class="required text" maxlength="200"
name="last_initial" />
</div>
</div>
</div>
<input id="btnRegister" name="btnRegister" class="submit" type="submit" value="Submit Your Answer" />
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#commentForm").validate();
// validate the comment form when it is submitted
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});
$("#commentForm").validate({
submitHandler: PostData
});
});
function PostData() {
debugger
var _firstName = commentForm.first_name.value;// $('#first_name').value; //first_name.value;
var _lastName = $('#last_initial').value; //last_initial.value;
var _city = $('#city').value; //city.value;
var _state = $('#state').value; //state.value;
var _country = $('#country').value; //country.value;
}
</script>
You’re hooking up the the
clickevent on the button, which happens before thesubmitevent on the form, instead use thesubmitHandlercallback option for.validate(), like this:…and remove this
clickhandler completely:The
submitHandleronly executes when the validation was successful, which would be what you want here.