homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

This 41 message thread spans 2 pages: 41 ( [1] 2 > >     
A Universal Script for Javascript Form Validation
I'm finally getting around to writing a universal script

 2:01 pm on Sep 21, 2008 (gmt 0)

This is something I've been conceiving for quite a while now, a universal script to validate any form fields.

The types I've got planned so far are:
Free text
Letters (including space but no symbols)
Both (like an address line)
Phone number
An email address
Dates (various formats)
Custom field (like a reference number, you'll be able to specify a character sequence)

Any other common things I've missed?

Other features will include, case transformation, phone number formatting, date validity, popup calendar, default text, force required fields, active/disable by checkbox/select....and finally, parent CSS class changing.

I'd also like any ideas and feedback you guys can think of to throw into this, of course it will be freely available for use and scrutinization when it's workable!

[edited by: Dabrowski at 2:02 pm (utc) on Sep. 21, 2008]



 8:38 pm on Sep 21, 2008 (gmt 0)

What is a "Free text" field? What would be considered invalid free text?

For Numbers, maybe split it into multiple types: Integer, Decimal (need to support . or , to mark the beginning of the decimal portion), etc.

Both (Letters + Numbers) = Alphanumeric, correct?

What format of phone numbers? US? International? UK? etc.


 12:00 pm on Sep 22, 2008 (gmt 0)

One that forced itself into my validation bag-o-tricks is "equate", as in, two fields that must be identical (commonly used for email, password).

And sometimes there are situations where no prerolled validation pattern will do, so I have a basic class for validation with Regex, and for inheriting more than one validation rule. For instance, "password must be greater than 6 characters long with no spaces, and contain at least one numeric character and one punctuation character".

A universal system should also be capable of "callbacks" - using AJAX to hit up a database, with a DAL that returns true/false. Example: "that username has been taken, please choose another"


 4:58 pm on Sep 22, 2008 (gmt 0)

another criteria for validation: length. Checks that the length of the value falls within a minimum and maximum.

optional parameter: whether the value gets a trim() before measuring length. default = true.

A length filter is useful for checking emptiness of a field. You just set minimum to 1 instead of 0 (the default). If maximum is null or undefined, that means no maximum, i.e. infinity


 7:40 pm on Sep 22, 2008 (gmt 0)

Great ideas guys!

What is a "Free text" field? What would be considered invalid free text?

Urrrr, yeah. Dunno why I put that one in. Anyone can write code to do bugger all!

For Numbers, maybe split it into multiple types: Integer, Decimal

Thats a good one, for prices etc...

Both (Letters + Numbers) = Alphanumeric, correct

Not sure, I'm not entirely certain if alpha technically includes any punctuation or not, so I've added an allow field, for spaces, separators (- and / for numbers, - and ' for letters), and punctuation.

What format of phone numbers? US? International? UK?

Should be easy enough to do all, if not exactly, acceptably. So e.g. 01211239876 would translate to 0121 123-9876. 18005551234 would translate to +1 (800) 555-1234. Maybe have a variable to set home country.

where no prerolled validation pattern will do, so I have a basic class for validation with Regex

I'll have to have a think about how that could be implemented.

A universal system should also be capable of "callbacks" - using AJAX to hit up a database, with a DAL that returns true/false. Example: "that username has been taken, please choose another"

Hmm, I think that may be too specific to write generically. That may be better left for your own code, or server side validation.

whether the value gets a trim()

It was always gonna get a trim, can't think of a reason why you'd disable it?

A length filter is useful for checking emptiness of a field

Was gonna use a requirement flag, same thing.

Some more info on the way I intend the custom field to work, specify a string, which is code for letters, numbers, or literal characters. Kinda like a very basic regex.
* = a letter
# = a number
@ = either
anything else = itself

*@## *** would be a UK car reg number.

Ooo I also missed times off my list, so, added the following types:
Decimal number


 9:50 pm on Sep 22, 2008 (gmt 0)

Well it's probably not that helpful, but I've always had an issue with plain English error messages (or lang. of your choice.) So you might want to think about that. Example:

var screen=newArray('Email','home_ph',work_ph');

So you could iterate through these and build an alert someone would understand, except this . . . .

for (n=0;n<screen.length;n++) {
if document.getElementById(screen[n].value == '') {
alert('The ' + screen[n] + ' field is required.');

Would produce

The Email field is required. (good enough . . .)
The home_ph field is required. (ACK!)
The work_ph is required. (ACK x 2!)

Everyone will know what home_ph means, right? Nope . .... so you could attempt to use spaces in id's (nope) or names that are closer,


But these are hardly "perfect" and require a compromise that would be more difficult than changing the script (modifying your page id methods or just settling for "good enough.") Currently I use two arrays, but as Fotiman pointed out, it's much better to use an associative array:

var screen=newArray('Email','home_ph',work_ph');
var eng=newArray('email address','home phone','work phone');
alert('The ' + eng[n] + ' field is required.');

So now you're just down to modifying the arrays for each project.

Food for thought.


 10:10 pm on Sep 22, 2008 (gmt 0)

I've decided to go down the CSS route for error displaying. One chunk I have on my test page so far looks like this.

It's probably better just to paste this into a test page rather than read through it.

Basically, on the middle input section here, I've appended "-error" onto the CSS class, ideally my script will append that onto the INPUT tags' parent tag. Hence adding a coloured background, and revealing the error message. You could even stick a little icon in there with a popup explaining the input type. Really it passes the buck on error reporting, this way is much prettier, and as you say there's no one-size-fits-all solution really.

margin: 0;padding: 0;
display: inline-block;
width: 150px;

.input-group {
padding: 5px 0;
width: 498px;
background: lightgrey;
border: 1px solid black;

.input-group .text {
margin: 0;padding: 0;
width: 130px;
margin-right: 10px;
border: 1px solid black;

.input-group .note {
font-size: 9px;
text-transform: uppercase;
color: gray;

.input-field {
padding: 0 5px;

.input-field INPUT .ok {border: 1px solid green;}
.input-field INPUT .not-ok{border: 1px solid red;}
.input-field INPUT .partial {border: 1px solid yellow;}

.input-field .error {
display: none;

.input-field-error {
padding: 5px;
background: #FF8844;

.input-field-error .error {
display: block;
font-weight: bold;
color: white;

<div class='input-group'>

<div class='input-field'>
<label>Any text here</label>
<input class='text' name='freetext' type='text'>

<div class='input-field-error'>
<label>Any text here</label>
<input class='text' name='freetext-required' type='text'>
<span class='note'>Required</span>
<span class='error'>You must enter something!</span>

<div class='input-field'>
<label>Any text here</label>
<input class='text' name='freetext-default' type='text'>
<span class='note'>Default text not allowed</span>
<span class='error'>You must enter something!</span>



 1:35 pm on Sep 23, 2008 (gmt 0)

My harshest criticism of this technique is that a user with no CSS enabled (as on some portable devices) will see error messages beneath every form field. I would suggest that error messages be generated in another way and injected into the DOM only when validation fails.


 2:56 pm on Sep 24, 2008 (gmt 0)

that a user with no CSS enabled

I hadn't thought of that. Although you could argue that that device probably wouldn't support JS either, so you wouldn't build the page in this way.

The idea was to give the control of the errors and styles to the page rather than the script for better integration.

I guess as well as changing the parents' class I could inject the <span class='error'> and give the option to set the text?

Foti, Rocky, What do you think?


 3:20 pm on Sep 24, 2008 (gmt 0)

I would lean towards injecting the error message. However, I would do it in a way that allowed the page to control where in the content the message would be injected. In other words, the page author could create a placeholder element that would get the error message, and if they didn't provide one, then one would be created for them.


 3:26 pm on Sep 24, 2008 (gmt 0)

* = a letter
# = a number
@ = either
anything else = itself

If it were me, I would swap * and @, because to me @ looks more like a letter and * is traditionally a wildcard to mean anything. So:

@ = a letter
# = a number
* = either
anything else = itself

But what if the "anything else" contains one of the tokens characters? For example, what if I wanted to match a string like:


I would suggest that if you're going to go the route or creating your own regex language, you'd need to specify an escape character as well. For example:

@ = a letter
# = a number
* = either
anything else = itself
\@ = a literal "@"
\# = a literal "#"
\* = a literal "*"
\\ = a literal "\"


 5:52 pm on Sep 24, 2008 (gmt 0)

oh my goodness

Why would you want to create your own Regex-like pattern matching language? Just use regex!

I was going to list the pros and cons of using regular expressions, but there are no cons and my brain returned a division by zero error.


 6:00 pm on Sep 24, 2008 (gmt 0)

>> device probably wouldn't support JS either

good point. It's very uncommon for someone to be JS enabled, and CSS disabled.

Yet in the platform I work on, that's one of the test cases we support. Everything in the DOM must be semantically correct as well as functionally robust. It does make things quite a lot more complex, but we haven't discovered a browser/agent/device yet that doesn't look and perform perfectly with our system.


 6:08 pm on Sep 24, 2008 (gmt 0)

Unlike httpwebwitch, I do think there are cons to using regex. The most obvious being that it's a very complex and intimidating language. My assumption is that you wanted something simple that anyone could use... regex is not the answer if that's the case.

If it were me, I'd probably do both. Create a simple language with a very minimal set of tokens (not forgetting something to escape those tokens) and let your program use either a string containing your simple-language pattern or a RegEx object.

2 cents.


 6:17 pm on Sep 24, 2008 (gmt 0)

I would lean towards injecting the error message

ok, then I'll look for an element with a class of something like 'error-message' and if there isn't one I'll stick a span in, in the style of my code posted above.


Use an email address type! :-D

Why would you want to create your own Regex-like pattern matching language

Trust me, I wouldn't even attempt to attempt that! Nothing that advanced.

What I had in mind really was for simple things like reference numbers, there are so many I couldn't possibly code all of them individually, but a simple way of creating a customised field (using Foti's slight change), examples:

car reg no UK.......X123 WYZ or AB08 CDE......@*## @@@
bank sort code......12-34-56..................##-##-##
BT account ref......AB12349876................@@########
HMRC PAYE...........123PP09876543.............###PP########
NI number...........XX 12 34 56 Y.............@@ ## ## ## @

You see what I mean?

An escape character might be handy, I guess some ref numbers could have a # or something in them.


 6:38 pm on Sep 24, 2008 (gmt 0)


Use an email address type! :-D

Ok, for that example, sure. But there may be other cases where an @, #, or * symbol are included in a string that's not a predefined type.

[edited by: Fotiman at 6:38 pm (utc) on Sep. 24, 2008]


 4:57 pm on Sep 26, 2008 (gmt 0)

Right, I'm starting to get some code together, taking a leaf or 2 out of Foti's book.

I've also added the types:


 4:52 pm on Oct 3, 2008 (gmt 0)

assumption is that you wanted something simple that anyone could use

Correct. Although I will add regex, that way an experienced coder could still use the script but hopefully customise it to his liking.

I've now got a very large test form, and some working code, and I've started to put the basics together.

I've been thinking about how to actually tell the script which boxes are which. I've come up with 2 possibilities so far, one of which will make you all shout at me a lot I think.

Idea 1 - hidden form fields:
<input type='hidden' name='formconfig' value='yourname; required; type, letters, allow, spaces; transform, capitalize'>


<input type='text' name='yourname'>

So basically the value string contains:
yourname - name of input box
required - will error on submit if not filled in
type, letters, allow, spaces - tells it to accept letters but allow spaces
transform, capitalize - capitalize the name, e.g. user types "john doe", changes to "John Doe".

With ; and , being major and minor command separators (which I've already added a way to change ;) ).

Idea 2 ... bring the fire ... an invalid property:
<input type='text' name='yourname' validate='required; type, letters, allow, spaces; transform, capitalize'>

I realise that's probably not 100% compatible, but I'm sure I've used that method before for something and it worked ok. I believe the W3C does say somewhere that any non standard properties should be added to the element?


 5:32 pm on Oct 3, 2008 (gmt 0)

Why does it need to be in the markup at all? You're talking about behavior, so why not make it a JavaScript object?

<script type="text/javascript">
items: [
{id:'yourname', req: true, type: 'letters', allow: 'spaces', transform: 'capitalize'},
{id:'yourname2', type: 'letters'}

In other words, pass in an object to your validator. This object has an 'items' property which contains an array of the fields to validate, as well as the rules to validate against.

This would be a much cleaner approach. It's unobtrusive and keeps all of your validation logic out of the markup.


 5:42 pm on Oct 3, 2008 (gmt 0)

Also, you could optionally pass in element references instead of "ids", and/or allow passing in the form name + input name instead of id. Gets a little sticky, but provides some flexibility. So maybe:

{el: 'yourname'} // If el is a string, getElementById
{el: document.getElementById('yourname')} // if el is an HTML Element, work on that
{el: {form:{name:'yourform',id:''},field:'yourname'}
{el: {form: document.getElementById('yourform'), field:'yourname'}

In other words, add some logic to allow for greater configurability so that users can specify which fields to validate with a variety of methods.

Just a thought.


 8:39 pm on Oct 3, 2008 (gmt 0)

First idea looks good. Second one just looks like it's overcomplicating things -- especially for me!

The only problem I see with the first method, is that will attempt to execute and validate as soon as it hits the script tag, which means the form may not be properly formed yet.

The advantage my way is that the validator uses onload to run and looks for the formconfig tags once the page is done. Also the input tags will be inside the relevant form. The script will be able to handle multiple forms on the page.


 3:39 am on Oct 4, 2008 (gmt 0)

Well, I didn't mean for that example to suggest that it would execute as soon as it hit the tag, but rather that you would store that configuration object and then when it came time to validate you would use those values to perform the validation, vs. looking in the HTML. My example would also be fired onload (or onDOMReady), but I didn't show that in the example.


 8:11 pm on Oct 4, 2008 (gmt 0)

onDOMReady would be useful, I'd rather use it but I didn't think it was supported in all browsers?

I'm really only interested in IE6, IE7 and FF, that's 94% according to:

And if the other few don't work the page will still be ok.


 4:23 am on Oct 5, 2008 (gmt 0)

Again, I gotta praise the Yahoo UI Library. They have their own onDOMReady method which works across all A-Grade browsers.


 10:26 am on Oct 6, 2008 (gmt 0)

I have been using a form Validation JS script successfully for years - in fact its most recent update was in 2006.


(Edit: Not sure if that URL is allowed here, in case not you need to go to Yahoo Groups and find the "Validation" group.)

you will have to join the Validation group to be allowed to get to the FILES menu :(, from there you need "Cross Browser" and then the "validation 3.1.5" ZIP file. In that is readme.htm. This has a description of all the validation types and methods supported.

It may give you some good ideas for your project.

In essence you include the relevant JS script on your page, and then add some "hints" to the Form fields - either directly in the INPUT tag, or using Javascript to "apply" them to the fields.


<input name="MyDate" type="text" display-name="Start Date" date="MM/YYYY" required="on" />

this will force the user to enter something in this field ("Required") and make sure that the Month/Year is valid.

There are methods for adding user-friendly display names to field, and suitable messages to be displayed, and so on.

There are also Pre/Post processing function hooks which can be used to customise the validation further - such as onbeforevalidate / onaftervalidate / onautosubmit

[edited by: Krispy2 at 10:42 am (utc) on Oct. 6, 2008]


 4:00 pm on Oct 8, 2008 (gmt 0)

They have used my second idea, invalid properties.

I've decided against that. I don't believe it can be 100% reliable as it's not standard code. The HTML validation gurus would have a field day with it.

I'm sticking with my hidden form fields idea. It's valid, and the most simple for other people to use.

The pre/post processing sounds like a good idea though, have you ever found it useful?


 5:10 pm on Oct 8, 2008 (gmt 0)

Yes, we have used that to intercept certain fields that needed some sort of one-off validation, for which we wrote a JavaScript function specfically


 7:12 pm on Oct 8, 2008 (gmt 0)

I took a quick stab at how I might do it, using JavaScript to define the fields to validate vs. putting it in the code. Note, this is a crude example, meant only as a proof of concept. In this example, I'm defining event handlers, whereas in a real world case you'd be better off using event listeners. Also, I'd move the JavaScript out to .js files.

This example demonstrates:
1. Your markup remains clean.
2. A class 'DaValidator', which can take the configuration data in the constructor or in an init method call. Public methods defined in the prototype object for memory efficiency.
3. Multiple instances of the validator. One demonstrates passing the config in the constructor, the other demonstrates passing it in the init method.
4. A callback method when the validator fails (useful for capturing the fields that errored and showing that to the user).

Hope this is helpful. At the very least, it was quick and fun. :)

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>Sample DaValidator</title>
<form action="" id="userForm">
First Name: <input id="firstname" name="firstname">
Price: <input id="price" name="price">
<input type="submit" value="submit">
<form action="" id="contactForm">
Phone: <input id="phonenum" name="phonenum">
Email: <input id="email" name="email">
<input type="submit" value="submit">
<!-- Scripts -->
<script type="text/javascript">
function DaValidator(oCfg) {
this.cfg = oCfg ¦¦ {};
DaValidator.prototype = {
init: function (oCfg) {
// Valid config object properties:
// items {Array} ...
// ...
this.cfg = oCfg;
validate: function (fn) {
var i, o, result = true;
var el, aStatus = [];
if (!this.cfg ¦¦ !this.cfg.items) {
// No items to validate
return result;
o = this.cfg.items;
for (i = 0; i < o.length; i++) {
el = document.getElementById(o[i].id);
// Check each of the possible validation properties
if (o[i].req) {
if (el.value.length == 0) {
result = false;
aStatus[aStatus.length] = {id:o[i].id, msg:'Missing required value on ' + o[i].id};
// if (o[i].type) {...}
// if (o[i].allow) {...}
// etc.
// fire the callback method
if (fn) {
return result;
<script type="text/javascript">
window.onload = function () {
var V = new DaValidator();
items: [
{id:'firstname', req:true, type:'letters', allow:'spaces'},
{id:'price', req:true, type:'email'}
var V2 = new DaValidator({
items: [
{id:'phonenum', req:true},
{id:'email', req:true}
function validatorCallBack (a) {
var i, str = '';
// We have the scope of the DaValidator instance, so we can
// access properties of the DaValidator instance using 'this'
if (this.cfg && this.cfg.items) {
alert('Number of items checked: ' + this.cfg.items.length);
for (i = 0; i < a.length; i++) {
str += a[i].msg + '\n';
document.getElementById('userForm').onsubmit = function () {
return V.validate(validatorCallBack);
document.getElementById('contactForm').onsubmit = function () {
return V2.validate(validatorCallBack);


 8:02 am on Oct 12, 2008 (gmt 0)

Here are some important things which are implemented in server-side validation libraries here.

  • Future Date (i.e. scheduling meeting etc. must be future)
  • Valid Date (is the date on the 31st Feb? etc.)
  • Greater Than FieldX (price ranges, date ranges, etc.)
  • Less Than FieldX (age at least 14 etc.)
  • UNIQUE (you absolutely need a callback ability via AJAX or similar to check if a username, etc. is unique)
  • Regex (support for typing REGEX directly)
  • URL (including http and https)
  • Relative URL (expecting a local link)
  • MATCHES (callback to find a matching record - i.e. send to named member)
  • Filter (do not permit a string containing one of listed words)
  • CAPTCHA (if you can check by callback before actual submission, that would be gold)
  • Exactly (equal to a predefined string; e.g. agree to TOS value must be exactly 1, signature box exactly 'USERS NAME', etc.)
  • Image/file type check

    I think you really should consider building this to be driven server side, data in a database, with generated Javascript code for the fields. You are going to have to do the server side validation anyway - and it'll be mostly the same thing. Nobody likes to do things twice!

  • jcaron

     9:41 am on Oct 12, 2008 (gmt 0)


    One very important point: DO NOT check the input ONLY via Javascript. You MUST check it again server-side (using PHP, Perl, ASP or whatever other language you use for your scripts). Don't forget that people can disable JS, and they can of course use other tools to send data to your server (curl, libwww, etc.), for good (automation) or bad (malicious) reasons.


    This 41 message thread spans 2 pages: 41 ( [1] 2 > >
    Global Options:
     top home search open messages active posts  

    Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
    rss feed

    All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
    Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
    WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
    © Webmaster World 1996-2014 all rights reserved