Reputation: 381
I am working on jquery validation with form action php submit. I created jquery validation using click function first time it's validate the input field on second click it's redirecting to form action url. How to prevent this using client side validation. How can i solve this.
<form action="test.php" method="post">
<input class="qemail" name="your-email-address" placeholder="Your email address" value="" type="text">
<textarea class="qmessage" name="your-enquiry" rows="8" placeholder="Your message"></textarea>
<input id="submit_sf" name="enquiry-submit" value="SUBMIT" type="submit">
</form>
$(document).ready(function(){
$('input[name="enquiry-submit"]').click(function(){
var email = $('.qemail').val();
var msg = $('.qmessage').val();
var email_regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(!email.match(email_regex) || email.length == 0 ){
if ($('.qemail').prev(".rvalidation").length == 0){
$('.qemail').before('<p class="rvalidation" style="position:relative; color: #000; font-size:12px;">Please enter a valid Details *</p>');
$(".qemail").focus();
console.log("email field is empty");
$(".qemail").focus();
//console.log("validate1"); \
return false;
}
//return false;
}
if(msg.length == 0){
console.log("message field is empty");
return false;
}
});
});
Upvotes: 0
Views: 154
Reputation: 499
The function() within the .click event can accept an argument for the event handler.
$('input[name="enquiry-submit"]').click(function(ev) { ...
You can use ev.preventDefault(); to keep the post from actually occurring until validation has passed. You'll need to manually trigger the form post though.
$('input[name="enquiry-submit"]').click(function(ev) {
ev.preventDefault();
...
}
Upvotes: 0
Reputation: 1863
change type = "button"
<button id="submit_sf" name="enquiry-submit" value="SUBMIT" type="button">Submit</button>
Upvotes: 1