Form validation does not happen
My form has some fields that are mandatory and I have marked them with class="required"
. I am writing the below jquery to validate this form, but it doesn't happen. I think either I am messing with calling the two functions or I am not getting the proper element through $(this)
.
<script type="text/javascript">
function validatemyForm() {
$('.required').each(function() {
if($(this).val() == "" || $(this).replace(/\s/g, '').length == 0)
{
$(this).insertAfter('<span>This is a Required Filed</开发者_如何学编程span>');
return false;
}
else {
$(this).remove();
}
})
return true;
}
</script>
I am calling the form, from the onsubmit event handler <form id="myform" onsubmit ="return validatemyForm();">
. Am I incorrectly using each
and this
of jQuery?
A number of things:
You can use
replace
on a String, whilst you use it on a jQuery object. There is no$(this).replace
. If you want to check for whitespace, you need the value, i.e.$(this).val().replace
.You use
$(this).insertAfter
which means that the input element is inserted after the span.$(this).remove
simply removes the input element which isn't what you're after either I think.You
return false
in theeach()
, but this doesn't return that value in thevalidatemyForm
function. In that function, you alwaysreturn true
.
I changed it to this to get it working: http://jsfiddle.net/DaDQT/6/.
Your function validatemyForm
always returns true. The return false
you have in there is inside the function passed to each
. validatemyForm
does not stop at this point.
The following should work as you expect it (untested code):
<script type="text/javascript">
function validatemyForm() {
var ok = true;
$('.required').each(function() {
if($(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0)
{
$(this).insertAfter('<span>This is a Required Field</span>');
ok = false;
}
else {
$(this).remove();
}
})
return ok;
}
</script>
精彩评论