Jump to content

How to prevent form submission upon validation failure with JavaScript

0
  dannyg1's Photo
Posted Sep 02 2009 10:05 AM

Batch validation checking typically operates from the submit event handler of the form element. Submission is aborted if the event handler evaluates to return false. Include the return statement in the event handler assignment, and let the validation function supply the Boolean value based on its findings:

    

You can implement batch validation by way of a master function that calls the individual validation functions as needed. To demonstrate, let's create a small form with numerous control types in it. Text fields execute real-time validation, while the form's submit event handler performs the batch validation. Both validation types use the validation functions shown in "How to perform common text field validations with Javascript" (either the string parsing or regular exp​ression varieties). Here's the form's HTML:

    

    First Name: 
Last Name:
Email Address:
Your Region:
Licensing Terms: I agree I do not agree
form>

You can see the form in the following figure, “A form of mixed input types”. As the user tabs and clicks through the form, typically the only validation taking place is in the email text box. Tabbing through the empty name fields without making any changes won't trigger the change event handlers there (another reason why batch validation is needed). In this form, we also want to make sure that a choice is made from a select element, and that a member of the radio button group is clicked (some designers might question delivering radio buttons without a default selection, but this example requires no initial selection).

A form of mixed input types

Attached Image

When the user clicks the Submit button, the validateForm() function executes to perform validations of all required form controls. The calls to the validations are cascaded so that if there are multiple errors and the user corrects the first one to be reported, subsequent clicks of the Submit button find an error lower in the form than a previous one:

    function validateForm(form) {

        if (isNotEmpty(form.name1)) {

            if (isNotEmpty(form.name2)) {

                if (isNotEmpty(form.eMail)) {

                    if (isEMailAddr(form.eMail)) {

                        if (isChosen(form.continent)) {

                            if (isValidRadio(form.accept)) {

                                return true;

                            }

                        }

                    }

                }

            }

        }

        return false;

    }

Validation functions for a select element and radio button group are not among routines in "How to perform common text field validations with Javascript", but are shown here:

    // validate that the user made a selection other than default

    function isChosen(select) {

        if (select.selectedIndex == 0) {

            alert("Please make a choice from the list.");

            return false;

        } else {

            return true;

        }

    }



    // validate that the user has checked one of the radio buttons

    function isValidRadio(radio) {

        var valid = false;

        for (var i = 0; i < radio.length; i++) {

            if (radio[i].checked) {

                return true;

            }

        }

        alert("Make a choice from the radio buttons.");

        return false;

    }

Note that the select element design assumes that the first item is an invalid choice.

All of the functions feed back to the main dispatching function. If any one validation fails, the dispatching function returns false to the submit event handler, forcing it to evaluate to return false and thus aborting the submission. But if all validations return true, the dispatching function also returns true to the event handler, allowing the submission to continue normally.

Relying on the submit event handler means that the user could disable Javascript in the client to bypass client-side validation. This is a good reason to duplicate validation on the server. But if you'd rather perform all validation on the client and you know that all users have scriptable browsers, consider using a button-type input element instead of a true submit-type input element. Let the button's click event handler invoke the batch validation function and (if validation succeeds) the submit() method of the form object. Under these conditions, the user can't submit the form with Javascript turned off.

Javascript & DHTML Cookbook

Learn more about this topic from Javascript & DHTML Cookbook, 2nd Edition.

In today's Web 2.0 world, Javascript and Dynamic HTML are at the center of the hot new approach to designing highly interactive pages on the client side. With this environment in mind, the new edition of this book offers bite-sized solutions to very specific scripting problems that web developers commonly face. Each recipe includes a focused piece of code that you can insert right into your application.

See what you'll learn


0 Replies