开发者

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:

  1. 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.

  2. 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.

  3. You return false in the each(), but this doesn't return that value in the validatemyForm function. In that function, you always return 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. validatemyFormdoes 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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜