Reputation: 1029
I've been banging my head against the wall trying to figure what I'm doing wrong here (form submits / does not validate). I'm not an expert, so I'm hoping someone a little smarter than me will be able to quickly catch what I'm doing wrong:
<script>
function validateForm(){
var first = $('#first_name').val();
if(first==null || first==''){
if ($('span:contains("Enter a valid first name")').length==0){
$(this).closest('div').addClass('has-error');
$(this).after('<span class="error" style="color:red;font-size:14px;">Enter a valid first name</span>');
}
return false;
}
var last = $('#last_name').val();
if(last==null || last==''){
if ($('span:contains("Enter a valid last name")').length==0){
$(this).closest('div').addClass('has-error');
$(this).after('<span class="error" style="color:red;font-size:14px;">Enter a valid last name</span>');
}
return false;
}
return false;
}
</script>
The html:
<form id="myid" method="POST" onsubmit="return validateForm()">
....a form...
</form>
I'm using similar syntax to validate form inputs on .focusout()
, and it works fine.
Upvotes: 0
Views: 32
Reputation: 2579
Assuming you want the form to act normally if there are no errors, you should have the function return true:
function validateForm(){
var first = $('#first_name').val();
if(first==null || first==''){
if ($('span:contains("Enter a valid first name")').length==0){
$(this).closest('div').addClass('has-error');
$(this).after('<span class="error" style="color:red;font-size:14px;">Enter a valid first name</span>');
}
return false;
}
var last = $('#last_name').val();
if(last==null || last==''){
if ($('span:contains("Enter a valid last name")').length==0){
$(this).closest('div').addClass('has-error');
$(this).after('<span class="error" style="color:red;font-size:14px;">Enter a valid last name</span>');
}
return false;
}
return true; // everything went okay !
}
Upvotes: 1
Reputation: 780663
The last
return false;
should be
return true;
You get there when there haven't been any validation errors. Returning false
tells the browser not to submit the form, you need to return something else. You can also just remove the line entirely, since anything other than false
allows the form to submit.
Upvotes: 1