Checking Your Work: Validating Input -- The Cool Stuff

By Curtis Dicken

Nesting Validation

When doing validation your goal is to make sure input is complete and accurate. However, too often validation ends up being a source of frustration for the user. When validating your forms you should always try to nest errors together wherever it makes sense. For example, if a user leaves a required item blank you don’t want an error message telling them they forgot something and an error telling them they formatted it wrong. The first error should suffice.

If you noticed in our custom validation example above we have nested our validation. We first checked to see if at least one box was checked. If no box was checked we throw an error and we are done. If at least one box is checked then our first validation operation passes and we move on to the next to see if the items checked make sense. By using this nesting method we never inundate the user with overlapping or redundant error messages.

Putting It All Together

Now that we have created all of our desired validation pieces we can put it all together using the nesting principles we just discussed and include inline validation messages for all of the validation errors.
<html>

<head>

    <title>Guestbook Validation Example</title>

</head>

<body>

<script type="text/javascript">

 

    function validateMyForm()

    {

        // Create validation tracking variables

        var valid = true;

        var validationMessage = 'Please correct the following errors:\r\n';

        // Common validation expressions

        var noNumbersExpression = /^[a-zA-Z]+$/;

        var numbersOnlyExpression = /^[0-9]+$/;

        var emailExpression = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

        var telephoneExpression = /^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$/;

        

        // Clear all inline validation messages before doing validation

        document.getElementById('errorFirstNameMissing').style.visibility='hidden';

        document.getElementById('errorFirstNameLettersOnly').style.visibility='hidden';

        document.getElementById('errorLastNameMissing').style.visibility='hidden';

        document.getElementById('errorLastNameLettersOnly').style.visibility='hidden';

        document.getElementById('errorTelephoneMissing').style.visibility='hidden';

        document.getElementById('errorTelephoneInvalid').style.visibility='hidden';

        document.getElementById('errorEmailMissing').style.visibility='hidden';

        document.getElementById('errorEmailInvalid').style.visibility='hidden';

        document.getElementById('errorYearsMissing').style.visibility='hidden';

        document.getElementById('errorYearsInvalid').style.visibility='hidden';

        document.getElementById('errorCountryNotSelected').style.visibility='hidden';

        document.getElementById('errorFavoriteMissing').style.visibility='hidden';

        document.getElementById('errorFavoriteInvalid').style.visibility='hidden';

 

        // Validate first name

        if (document.getElementById('TextFirstName').value.length == 0)

        {

            validationMessage = validationMessage + '  - First name is missing\r\n';

            document.getElementById('errorFirstNameMissing').style.visibility='visible';

            valid = false;

        }

        else

        {

            // Validate first name is all letters

            if (document.getElementById('TextFirstName').value.match(noNumbersExpression))

            {

                // Do nothing

            }

            else

            {

                validationMessage = validationMessage + '  - First name must contain letters only\r\n';

                document.getElementById('errorFirstNameLettersOnly').style.visibility='visible';

                valid = false;

            }

        }

        

        // Validate last name

        if (document.getElementById('TextLastName').value.length == 0)

        {

            validationMessage = validationMessage + '  - Last name is missing\r\n';

            document.getElementById('errorLastNameMissing').style.visibility='visible';

            valid = false;

        }

        else

        {

            // Validate first name is all letters

            if (document.getElementById('TextLastName').value.match(noNumbersExpression))

            {

                // Do nothing

            }

            else

            {

                validationMessage = validationMessage + '  - Last name must contain letters only\r\n';

                document.getElementById('errorLastNameLettersOnly').style.visibility='visible';

                valid = false;

            }

        }

        

        // Validate telephone

        if (document.getElementById('TextTelephone').value.length == 0)

        {

            validationMessage = validationMessage + '  - Telephone is missing\r\n';

            document.getElementById('errorTelephoneMissing').style.visibility='visible';

            valid = false;

        }

        else

        {

            // Validate telephone formatted properly

            if (document.getElementById('TextTelephone').value.match(telephoneExpression))

            {

                // Do nothing

            }

            else

            {

                validationMessage = validationMessage + '  - Your telephone number appears to be invalid\r\n';

                document.getElementById('errorTelephoneInvalid').style.visibility='visible';

                valid = false;

            }

        }

        

        // Validate email

        if (document.getElementById('TextEmail').value.length == 0)

        {

            validationMessage = validationMessage + '  - Email is missing\r\n';

            document.getElementById('errorEmailMissing').style.visibility='visible';

            valid = false;

        }

        else

        {

            // Validate email formatted properly

            if (document.getElementById('TextEmail').value.match(emailExpression))

            {

                // Do nothing

            }

            else

            {

                validationMessage = validationMessage + '  - Your email address appears invalid\r\n';

                document.getElementById('errorEmailInvalid').style.visibility='visible';

                valid = false;

            }

        }

        

        // Validate years on internet

        if (document.getElementById('TextInternetYears').value.length == 0)

        {

            validationMessage = validationMessage + '  - Years using internet is missing\r\n';

            document.getElementById('errorYearsMissing').style.visibility='visible';

            valid = false;

        }

        else

        {

            // Validate years is a whole number

            if (document.getElementById('TextInternetYears').value.match(numbersOnlyExpression))

            {

                // Do nothing

            }

            else

            {

                validationMessage = validationMessage + '  - Years using internet must be a whole number\r\n';

                document.getElementById('errorYearsInvalid').style.visibility='visible';

                valid = false;

            }

        }

        

        // Validate coutry selected

        if (document.getElementById('SelectCountry').value == 'Select your country...')

        {

            validationMessage = validationMessage + '  - Please select your country\r\n';

            document.getElementById('errorCountryNotSelected').style.visibility='visible';

            valid = false;

        }

        

        // Validate at least one favorite website checkbox is checked

        if (

            document.getElementById('CheckboxHtmlGoodies').checked == false &&

            document.getElementById('CheckboxWDVL').checked == false &&

            document.getElementById('CheckboxInternet').checked == false &&

            document.getElementById('CheckboxJavaScript').checked == false &&

            document.getElementById('CheckboxNone').checked == false

            )

        {

            validationMessage = validationMessage + '  - Please select at least one favorite website option\r\n';

            document.getElementById('errorFavoriteMissing').style.visibility='visible';

            valid = false;

        }

        else

        {

            // Passed initial validation - now make sure None is not selected with other options

            if (

                document.getElementById('CheckboxNone').checked == true &&

                    (

                    document.getElementById('CheckboxHtmlGoodies').checked == true ||

                    document.getElementById('CheckboxWDVL').checked == true ||

                    document.getElementById('CheckboxInternet').checked == true ||

                    document.getElementById('CheckboxJavaScript').checked == true

                    )

                )

            {

            validationMessage = validationMessage + '  - None should not be selected with other favorite website selections\r\n';

            document.getElementById('errorFavoriteInvalid').style.visibility='visible';

            valid = false;

            }

        }

        

        // Display alert box with errors if any errors found

        if (valid == false)

        {

            alert(validationMessage);

        }

        

        return valid;

    }

    

</script>

 

<form onsubmit='return validateMyForm()'>

    First Name:

    <input id="TextFirstName" type="text" />

    <span id="errorFirstNameMissing" style="visibility:hidden;">*Please provide your first name.</span>

    <span id="errorFirstNameLettersOnly" style="visibility:hidden;">*First name must contain letters only.</span>

    <br />

    Last Name:

    <input id="TextLastName" type="text" />

    <span id="errorLastNameMissing" style="visibility:hidden;">*Please provide your last name.</span>

    <span id="errorLastNameLettersOnly" style="visibility:hidden;">*Last name must contain letters only.</span>

    <br />

    Telephone:

    <input id="TextTelephone" type="text" />

    <span id="errorTelephoneMissing" style="visibility:hidden;">*Please provide your telephone number.</span>

    <span id="errorTelephoneInvalid" style="visibility:hidden;">*Your telephone number appears to be invalid.</span>

    <br />

    Email:

    <input id="TextEmail" type="text" />

    <span id="errorEmailMissing" style="visibility:hidden;">*Please provide your email.</span>

    <span id="errorEmailInvalid" style="visibility:hidden;">*Your email appears to be invalid.</span>

    <br />

    Country:

    <select id="SelectCountry">

        <option value="Select your country..." selected="selected">Select your country...</option>

        <option value="Canada">Canada</option>

        <option value="France">France</option>

        <option value="United Kingdom">United Kingdom</option>

        <option value="United States">United States</option>

    </select>

    <span id="errorCountryNotSelected" style="visibility:hidden;">*Please select your country.</span>

    <br />

    How many years have you been using the internet?

    <input id="TextInternetYears" type="text" />

    <span id="errorYearsMissing" style="visibility:hidden;">*Please enter the number of year you have been using the internet.</span>

    <span id="errorYearsInvalid" style="visibility:hidden;">*Years using internet must be a whole number.</span>

    <br />

    Add to mailing list?

    <input id="RadioMailingListYes" type="radio" name="MailingList" checked="checked" />

    Yes

    <input id="RadioMailingListNo" type="radio" name="MailingList" />

    No<br />

    Favorite websites?

    <input id="CheckboxHtmlGoodies" type="checkbox" />

    HtmlGoodies.com

    <input id="CheckboxWDVL" type="checkbox" />

    wdvl.com

    <input id="CheckboxInternet" type="checkbox" />

    Internet.com

    <input id="CheckboxJavaScript" type="checkbox" />

    JavaScript.com

    <input id="CheckboxNone" type="checkbox" />

    None

    <span id="errorFavoriteMissing" style="visibility:hidden;">*Please select at least one checkbox.</span>

    <span id="errorFavoriteInvalid" style="visibility:hidden;">*None cannot be selected with favorite websites.</span>

    <br />

    <br />

    <input id="ButtonSubmit" type="submit" value="Submit" /><br />

</form>
</body>

</html>

Conclusion

Validation may take some extra work to get up and running but it is worth it to get the input you need from your users. Our illustration above shows you many of the most common forms of validation but there are others as well such as:
  1. Input is within a desired range (e.g. between 10 and 20 characters)
  2. Input conforms to a password standard (e.g. at least 8 characters with 2 numeric and 1 symbol)
  3. Input of one text box matches another text box (e.g. email and email confirmation)
Of course, you can customize just about any validation that you can imagine. Just remember, thorough validation translates into fewer data problems later.

Lastly, as I mentioned before, you can save yourself some coding time by creating separate functions to handle specific validations. This will reduce the amount of coding you have to do and allow you to create a validation library that you can reuse on all of your projects. An example of a function to handle validating input as an email address might look like:

function emailValidator(myElement)

{

          var emailExpression = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

          if(myElement.value.match(emailExpression))

          {

                return '';

          }

          else

          {

                return '  - Your email address appears invalid\r\n';

          }

}
Happy validating!


Page 2 of 2

Previous Page
1 2
 

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date