Easier Javascript Form Validation
I was racking my brain trying to find the best way to do form validation across a huge application, and I knew what I wanted to do. I wanted to implement a single function I could use to validate every form, without needing to resort to all kinds of manual coding.
I decided to use the class attribute for a little more than formatting. It's an ideal space to use for ad-hoc properties, since it allows as many class names as you want to put into a single tag.
Here's a basic form:
Notice the class names above. I've used 'required' as the class for the first input, and 'min20' for the second. I want required to mean the field cannot be blank, and I want min20 to mean the field must contain at least 20 characters in order to be valid.
Here is the validate function, which takes a form object as a parameter:
-
function validate(frm) {
-
var elms = frm.elements;
-
var numElms = elms.length;
-
-
for (var i = 0; i <numElms; ++i) {
-
if ( (/required/).test(elms[i].className) && !elms[i].value) {
-
elms[i].focus();
-
alert('You need to fill in this field to continue...');
-
return false;
-
}
-
-
if ( (/min20/).test(elms[i].className) && elms[i].value.length <20) {
-
elms[i].focus();
-
alert('This field requires at least 20 characters in order to continue.');
-
return false;
-
}
-
}
Now, those error messages suck. You'll want to do better, possibly using the name of the element, or the title attribute, or something else that will help it be more descriptive. That's outside the scope of this post, I'm just showing the mechanism for validation, bells and whistles on it are up to you.
~A!