JavaScript Form Validator

This is an updated and improved version of AJAX Generic Form Parser

Our updated JavaScript code is smaller, prettier :) and more powerful (just).

That’s nice, but what does it do?
Well it validates your form stupid!! as with most (if not all?) posts on this website, the script is simple, easy to follow and not jam packed with to many features. Basically this script will look for required fields (which you specify in your form.. I’ll come to this later) and if a required field is empty, it will through up a JavaScript alert box telling the user (and prevent the form from being submitted).

Before I present to you the Code Example, I’ll explain a little about how to configure your form and make certain fields required.
For simplicity, I’ve chosen to make use of the fields ‘Title’ tag. This is where you make fields required.

For example: < input type="text" name="FirstName" title=”required” >

Note: The script will support the following form field types:

  • Text
  • Textarea
  • Password
  • Select

Just to recap. To make any of the supported fields required, just add title=”required”!

Triggering the form to call the JavaScript Validation Script:
In order for the form to call the JavaScript and check all the required fields, we need to prevent the form from submitting. In order to achieve this, we will use the onSubmit event on the form tag. Example:

< form name="myForm" method="post" action="process.php" onSubmit=”return myForm.check(this)” >

We must use return before the function call, this tells to form ‘do not submit the form unless the function returns true’.

The JavaScript form Validator Script


As you can see, this is nice and easy to follow. Nothing to fancy, but believe me this wee function can save a lot of time, especially if you build a lot of forms.

Why does it not do more complex validation?
Simple, because I like to keep things nice and easy (and I don’t do complex)…. The last thing I want to do is give you a headache. Like everything on this site, this is just an example. Please feel free to use and enhance it to fit better with your own needs.

Before I go, I’d better mention that the JavaScript function will strip out any leading and trailing whitespace before the validation is done. There is also a little function to strip out HTML tags (it’s not being used in the above example, but you can make use of this on a field basis by using the onFocus event!!), Just a little bonus!!

1 Comment on JavaScript Form Validator number two

  1. proweb says:

    I would love a form that will prevent HTML / external links from being submitted.

    Can you pls provide sample code for this?

    Thx for the great form example code!