Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Is this a good form validation script? I'm using jQuery.

$(document).ready(function() {

    $("form").submit(function() {

        var shouldSubmit = true;

        $(this).children(":input:not(:button, [type=\"submit\"], [type=\"reset\"])").each(function() {

            if ($(this).val() == "")
            {
                shouldSubmit = false;
                return shouldSubmit;
            }

        });

        if ($("input:checkbox").length > 0)
        {
            if ($("input:checkbox:checked").length == 0)
                shouldSubmit = false;
        }

        if ($("input:radio").length > 0)
        {
            if ($("input:radio:checked").length == 0)
                shouldSubmit = false;
        }

        if (shouldSubmit == false)
            alert("All form fields must be filled out.");

        return shouldSubmit;

    });

});

Please tell me if there is anything else I should include. Remember it is only meant to be basic.

share|improve this question
    
Have a look at this method: api.jquery.com/is You can save some work by doing something like if($("input:radio").is("checked)). Also you can just return false right away instead of setting a boolean then returning false. –  Jonny Sooter Jul 16 '13 at 16:39

1 Answer 1

The if statements could be cleaner:

    if ($("input:checkbox").length > 0 && $("input:checkbox:checked").length == 0)
    {
        shouldSubmit = false;
    }

    if ($("input:radio").length > 0 && $("input:radio:checked").length == 0)
    {
        shouldSubmit = false;
    }

    if (!shouldSubmit)
    {
        alert("All form fields must be filled out.");
    }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.