简体   繁体   中英

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, ie $(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 . 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM