Javascript Form Validation Template Code

I found this code snippet in a four year old email that I had sent myself. This is the basic code layout that I use for form validation. What is nice about it is that it will parse the whole form and compile a list of all the form validation errors to present to the user at once, instead of presenting it to the user one field at a time and making them hit the submit button over and over again to get the form right.

<script type="text/javascript">
function verify() {
    var valid = true;
    var info = "Please correct the following:";

    // Below are some example tests that can make the valid flag false and
    // add text to the error message.

    if(document.getElementById('name').value == "") {
        info += "\n - enter your name";
        valid = false;
    }

    if(document.getElementById('zip').value.length != 5 ||
       document.getElementById('zip').value.match(/[^0-9]/g) !== null) {
        info += "\n - zip must be five numbers";
        valid = false;
    }

    // The above are just examples you can add as many tests as you want.

    if(!valid) {
        alert(info);
    }

    return valid;
}
</script>

The validation function maintains a flag that tracks whether any errors have been found. You can do as many tests on the form as you want and keep adding to the error message so the user can see everything that is wrong with the form all at once.

Leave a Reply

{
}