Tiffany B. Brown

a mish-mosh of stuff

A generic(-ish) JavaScript form validator function

I tried my hand at developing a reusable form validator function with JavaScript and the DOM. It checks:

  • Whether required fields are empty (where class=”required”)
  • Whether e-mail addresses are valid (where the field name is ‘email’ or ‘Email’)
  • Whether phone and fax numbers match one of several formats (404-555-5555, 404 555 5555, (404) etc. where the field name is ‘phone,’ ‘Phone,’ ‘fax’ or ‘Fax’).

If any errors are found, it will update a showErrors document fragment, and the form will not be submitted.

Yeah, it’s only mildly impressive, but if you knew where I was with JavaScript and DOM scripting six months ago, you’d be proud of me :-) .

Keep in mind that this does not work if JavaScript is turned off. In other words, don’t rely on it for final data validation. Use a server-side solution.

See the form check script in action, or download it [ZIP] file. Use it or modify it to your heart’s content. Post fixes or suggested improvements in the comments.

  • mike

    if(errors){ document.getElementById('showErrors').innerHTML = '<ul>'+errors+'</li>'; return false; }

    Should be '<ul>'+errors+'</ul>';

    Otherwise looks pretty good.

  • mike

    if(errors){ document.getElementById('showErrors').innerHTML = '<ul>'+errors+'</li>'; return false; }

    Should be '<ul>'+errors+'</ul>';

    Otherwise looks pretty good.

  • http://www.tiffanybbrown.com/ tiffany

    D’oh. Thanks for pointing that out. It’s fixed now.

  • http://www.tiffanybbrown.com/ tiffany

    D’oh. Thanks for pointing that out. It’s fixed now.