wForms Input Validation Explained
This post is part of the wForms Documentation. wForms is an open-source javascript library that adds commonly needed behaviors to traditional web forms without the need for any programming skill.
For additional help, visit the wForms forum.
The purpose of the input validation in wForms is to help users fill out a form
correctly, by defining required fields and allowed formats and by providing appropriate
error messages when the condition for submission are not met.
Example of Form Validation (click on submit)
Implementation
If you use the form builder, you don’t have to worry about these details, but to use the wForms input validation on your own web forms, follow the following steps:
- Enable the wForms extension by adding the following code to the <head> element of your page:
<script type="text/javascript" src="wforms.js" ></script> - Add any of the following classes to your input fields:
- required
- Field value cannot be empty. Use it on any field type (<input>, <select>,<textarea>).
- validate-alpha
- Allows only alphabetic characters ([a-z], can be modified for localization purpose). Allows an empty value.
- validate-alphanum
- Allows number and alphabetic characters, no ponctuation or exotic characters (can be modified for localization purpose). Allows an empty value.
- validate-date
- Allows a date, in any format supported by the local browser. Allows an empty value.
- validate-email
- Allows only a valid email syntax (someome@somewhere.somext). Allows an empty value.
- validate-integer
- Allows only a number (digits). Allows an empty value.
- validate-float
- Allows float numbers (ex: 0,00). Allows an empty value.
You may use ‘required’ in combination with any other class. For instance:
<input type="text" name="wf_Yourname" class="validate-alpha required"/> - To require at least one response to a multiple-choice question, add the class ‘required’ to the parent element (the container). For instance:
<div class="required">
<input type="checkbox" name="something" … />
<input type="checkbox" name="somethingelse" … />
<input type="checkbox" name="anothersomething" … />
</div> - Add the following CSS rules to your stylesheet to control the look of the error messages:
.errFld {border: 1px solid #F00; /*... or any other css properties ... */}
.errMsg { color: #C33; /*... or any other css properties ... */ }
Update: Comments are now closed for this post, but you can go to the wForms forum if you have any question or comment. Thanks !
April 25th, 2005 at 6:32 pm
Using:
If I click submit with out entering anything I get the required field error message as expected. But then I enter a value of ‘87343′ and click submit I still get the required field error message and not the alpha only error message. Why does the error message not update to the correct message?
April 25th, 2005 at 6:38 pm
Oops.
Using: <input type=”text” name=”foo” class=”validate-alpha required”>
April 25th, 2005 at 8:09 pm
Josh.. you’re a fine beta-tester. The error message is indeed not updated. I will fix that in the next update of wForms (sometimes early this week).
April 26th, 2005 at 10:43 pm
Is it mandatory that an Error Box pops up if validation fails? Can a message be displayed in red at the top of the page instead?
Also, are there plans to have more validation rules (perhaps all the ones covered here: http://www.peterbailey.net/fValidate/types/blank/ ) ? What about the ability to enter custom validation rules?
This is a very useful tool!!
April 26th, 2005 at 11:13 pm
Omkar, I’m working on a wForms customization documentation. I will post it today or tomorrow.
I’ll explain how to add custom validation and change some default behaviors in wForms.
As for adding new validation rules, It’s actually quite difficult to get someting robust enough to be of any use. Phone numbers are a good example.. there are just too many valid variations.
What new rule would you find useful ?
April 27th, 2005 at 2:27 am
That’s great news regarding the customization!
In regards to additional validation rules, I thought there might be a nice way to leverage the work Peter Bailey has done with fValidate in the above link. I’m not sure if this even makes sense to do but it seems fValidate has a pretty good number of validation rules already defined.
April 28th, 2005 at 12:43 am
Omkar, I posted the info on customization here.
Peter Bailey has done a nice job with fValidate, but I can’t use it as is (in part because it relies on invalid markup). Also, I try to keep the source code lean by implementing only the most useful validation routines.
The additional validation options I’m considering now are :
- text length
- time
And maybe phone and zip codes, but it seems superfluous..
May 3rd, 2005 at 5:58 pm
I need these rules:
- Valid URL (according to the RFC)
- Minimum text length
- Comparison (e.g. for password and repeat password fields)
- Option for specifying date format(s) allowed (e.g. dd-mm-yyyy only, automatically replacing / and . with - and so on)
I assume the email validator conforms to the RFC for email addresses? If not, it should
May 3rd, 2005 at 9:12 pm
Uffe, thanks for your feedback.
The valid url and the field comparison are better suited in a custom validation routine. I don’t think they are used often enough to be worth including in wForms.js (which is already over 1000 lines long).
I’m not sure what to do about minimum text length. In what situation would you need it ?
As for date format, I agree that there’s a need for more options. I’ll work on that eventually, but string formatting (replacing - and / ) should be the job of the server.
And no, the email validator does not conform to the RFC. I have yet to see an email validation routine that follows the RFC and is not completly overblown.
May 4th, 2005 at 12:59 am
Regarding minimum text length it could be for user chosen passwords that should be maybe minimum 6 characters long.
So how do you judge whether something should be a built-in validation or a custom one? I think the ones I mentioned are used quite a lot actually. I have no problem writing custom validations, but if I do write any, I would like them to be separated from the rest of wForms so that updates from you won’t overwrite my custom validations. (I haven’t checked the code to see if it’s already so)
Regarding email validator, well perhaps it’s a bit too much to make it conform to the RFC, but it definitely should do more than just check for user at host dot domain. I built a validator once that implemented almost all of the rules found in the RFC and yes it was maybe a few hundred lines of code, but it certainly reduced the number of bogus addresses submitted because the user suddenly had to be all creative about making up an address that looked real
June 10th, 2005 at 8:01 am
Cédric,
Congratulations on your efforts … it’s a great concept.
Any chance you might incorporate something to put the focus in the first required field the visitor failed to fill out? By the way, I stumbled across your 4213miles site a while back … very interesting. Makes me want to refresh my high school french so I can comprehend your culture shock (french) commentary … although I did get the “‘Entrée’” bit.
Thanks again for your fine work, and best of luck. And please forgive me for fiddling with the css … I couldn’t help it.
Eric Hobart
June 12th, 2005 at 6:03 pm
I see that form validation rules are added as a class, but what if I already have to apply a class to a form field, for example, I have:
How do I add the validation rules AND keep my class?
Thanks,
Bojan
P.S. This stuff is awesome, will use in all my projects. Keep up the good work
June 12th, 2005 at 10:22 pm
Bojan, there’s no limitation to the number of classes you can have in the class attribute. Just separate them with a space.
For instance, class=”validate-alpha required yourclass anotherclass”
June 12th, 2005 at 10:50 pm
Eric, your css looks great, you’re welcome to submit it to the Form Garden”, if you want.
As for the focus on the first error, yes definitively. I should have done it already. I’ll add it to the next update.
June 13th, 2005 at 7:04 pm
Thanks cedsav!
Tell me, has anyone written a custom validation that does comparison of fields (e.g. checks if two fiels are equal)?
I am a PHP programmer, so I stink at JavaScript, although I need it
June 13th, 2005 at 8:39 pm
Bojan, I posted the code sample for a custom validation w/ field comparison on the wForms Customization page.
July 15th, 2005 at 1:44 am
Hello,
I’ve been trying to get wforms working in combination with my Movable Type installation (installing things as mentioned on http://bbuchs.f2o.org/archives/2005/06/23/ajax-ified_weblog/). Things just work great – if there is only one form on the page. On the project I’m currently working on I have more than one form (multiple entries each with a comment form) which seems to break wforms. While IE and Safari ignore any wform-events but pass everything to Prototype (and thus make it working), FireFox just breaks and completely ignores wforms. Of course I have tried to find something helpful first, but I just seem to be out of luck.
What could I possibly doing wrong?
Thank you very much in advance,
Ben
P.S.: I’m currently working on http://zeitgeist.binaergebaeu.de - click on “Kommentare”, type in something, hit “» Senden”, feel free to browse the source, etc., pp.
July 15th, 2005 at 1:56 am
Ben, wForms expects to see a ‘type’ attribute for all INPUT tags.
On your form, replace:
<input id=”email” name=”email” class=”validate-email required” />
with
<input type=’text’ id=”email” name=”email” class=”validate-email required” />
July 16th, 2005 at 3:47 pm
After some trial and errors (well that’s a way to program
), and thanks to the great help of Cedric, I was finally able to get wforms running. I won’t go into deep detail, but if you happen to have several forms on a page and lots of javascript with lots of functions (64 kbytes for me, no, I haven’t optimitez the code yet), Firefox will behave extremely annoying by ignoring setted variables und functions in other .js, so that’s why I put all my custom validation stuff at the top of the wforms.js, et voilá, it works.
July 18th, 2005 at 8:32 pm
Hi,
is there a posibility to add the class “required” to a table, e.g. to tr?
My example:
<table>
<tr class=”required”>
<td> course</td>
<td> <input type=”checkbox” />course A</td>
<td> <input type=”checkbox” />course B</td>
</tr>
(Much easyer, I have more rows of this..)
Thanks,
Beate
</table>
July 31st, 2005 at 1:54 am
wForms is great!
But i would like to know if its possible to disable the messages that appear under fields that I set as required.
ie. the messages that say “This field is required”. however, i would still like to keep the field box color change and the popup alert message. these text messages really screw up my table layout when they appear.
I read through the customization page, and i didnt really understand it…then again, i am new to javascript.
July 31st, 2005 at 6:47 am
fc, just add this to your CSS:
.errMsg { display: none; }
July 31st, 2005 at 8:29 pm
thanks alot, thats exactly what i wanted to do.
September 10th, 2005 at 12:05 am
the work you’ve done on wForms is awesome. thanks so much for it. i want to change the error behavior messages, though, and since I have only a little js knowledge i was hoping someone could help me out.
for my layout, the current behavior breaks the visual relationship between the label and the field. more ideal would be if I could highlight the whole block element (label and field) and display the message at the top of the highlight box. My lame attempt to sketch what I am talking about:
—————————————-
| ! This field is required ! |
| _____________ |
| Username: |_____________| |
| |
—————————————-
Could someone help me figure out how to code something like this? Thanks for the help.
September 10th, 2005 at 12:08 am
sorry, it seems the comment system removed the white spaces, so the sketch is useless…
September 10th, 2005 at 1:03 am
Jace, you can create placeholders for error messages. The id attribute of the placeholder must match the id of the field, plus the ‘-E’ suffix.
For instance:
<span id=’myfield-E’></span>
<input type=’text’ id=’myfield’ … />
This will cause the error message to be displayed inside the SPAN (which you can place anywhere in the page).
You could also try to move the label and the input inside the placeholder span, so you can highlight both the label and the input with .errMsg CSS class, but this should result in the error message being displayed after the input field.
Anyway.. give it a try and let me know if it works for you.
September 16th, 2005 at 8:27 pm
a great article on usability of XMLHttpRequest can be found here :
http://www.baekdal.com/articles/usability/usable-XMLHttpRequest/
i beleive we can all benefit if its implemented into wForms!
September 18th, 2005 at 12:57 pm
ok, so I’ve been trying to figure this out for the past few days now and I am still having trouble. I am a total noob to javascript. I’ve been looking at the source for multiple other form validators including fValidate and Tigra and trying to figure out how their scripts work to display errors. I figured I could mod them with the wForms variables and get the behaviors I wanted… not so apparently.
cedric, thanks for the quick reply. am I hard-coding an empty span element into the XHTML for each form element in order to get that done? is there a cleaner way?
what would be my ideal situation is to reassign the class name of the form element so that the entire element (label, field, and field hint) could be styled to highlight red (or something of the sort). the error message would be presented at the top of the highlighted area, so maybe the script would have to write a div and p element to have the display come out right. additionally, instead of an alert box, a new box on the page displaying either that errors occurred, or even specifically which errors occurred. Essentially, I’ve described the way that Adam Kalsey has found to do it PHP, and Jeff Howden has found to do it in ColdFusion. What I need is a way to integrate that functionality as JS in wForms.
I can’t do it myself because I don’t know any javascript. I’m trying to learn, and I’ve worked at it for the past few days, but I need that behavior long before I’ll know enough to do it right on my own. So this is my official plea to anyone who could write up such a customization and share it with us/me. I know it’s a lot to ask, but I figured it was worth a shot in the OS community! Cedric, maybe this is something you could work up for future wF releases? Again, thanks for wForms in the first place! and thanks to all who might help.
September 30th, 2005 at 1:52 am
Jace, yes, hard-coding the empty tags is not a very clean solution, but that the one that give you the most flexibility.
You can also tweak wforms.js to change the default positionning of error message. For instance:
if you replace line 704:
fl.parentNode.insertBefore(fe,fl.nextSibling);
by
fl.parentNode.insertBefore(fe,fl);
The error message will appear *before* the label (assuming the label id follows this convention: id_of_the_field + ‘-L’ suffix. Example: <label for=”firstname” id=”firstname-L”> … </label>)
If you don’t want the alert box, set this.showAlertOnError to false (line 60 in wforms.js).
October 3rd, 2005 at 9:02 pm
cedsav - “Beate” touched on this earlier here, but I didn’t see any response. I have a couple of nested ordered lists, each containing a label and radio input. User must make one selection from the list to be a valid submission. Giving the UL tag a class of “required” doesn’t trigger the validation for the nested inputs; neither does wrapping the whole thing in a span/div with the “required” class.
In the past, I’ve just used CSS to style a simple list of radios/labels to look like a list, but that’s not really feasable with a nested tree. Any suggestions?
October 4th, 2005 at 12:58 am
Bryan & Beate (sorry for the missed comment)… the ‘required’ class *should* work when set on a table or a div (not a UL, but that would be easy to support). Do you have a test case I can look at ?
Thanks.
October 6th, 2005 at 2:36 am
Sure thing:
http://www.bryanbuchs.com/wforms_demo.php
I hadn’t tried the required class on a TABLE yet, and it looks like that works as it should. That’s certainly another option for me to consider, but I would like to see UL/OL -> LI support (semantic code structure and all…)
October 6th, 2005 at 2:58 am
To support ‘required’ on OL/UL/LI tags you’ll need to add the following in wForms.js (around line 563).
case “UL”:
v = checkOneRequired(x[i]); break;
case “OL”:
v = checkOneRequired(x[i]); break;
case “LI”:
v = checkOneRequired(x[i]); break;
I’ll add this in the next update of wForms.js
October 6th, 2005 at 6:26 pm
I was hoping it would be that simple… so I dug around and tried it on my own yesterday. Unfortunately, it doesn’t seem to work. I posted a modified version of wForms.js and an updated demo to the same page:
http://www.bryanbuchs.com/wforms_demo.php
October 14th, 2005 at 4:08 pm
Can wforms do field validation on change (onchange)?
October 14th, 2005 at 7:23 pm
Ralph, see my response to Andy over here: http://www.formassembly.com/blog/wforms-customization/#comment-896
(he uses onblur, but it’s similar for onchange).
October 17th, 2005 at 1:12 am
Thanks for the quick reply, but I already found that one, modified it a bit and seems to works perfectly.
for those who are interested:
– begin –
if (x[i].tagName.toUpperCase()==”INPUT”) {
wu.XBrowserAddHandler(x[i],’change’,this.formValidation);
}
– end –
offcourse if you validate field by field, you also need the focus to stay on a field when it triggered a error.
first i created a little function for this in customization.js
– begin –
function setfocus(fl)
{
global_fl = fl;
setTimeout( ‘global_fl.focus()’, 10 );
}
– end –
then a inserted a line at rule 650 making a call to this function
– begin –
setfocus(srcE);
– end –
Next project is trying to get everything to work without touching wforms.js and put all modification in de customization.js.
October 25th, 2005 at 11:12 pm
Some other validation checks that I could see as useful would be
1. telephone format
2. ssn format
but again this may be best suited for a custom script. I’m still al little fuzzy about how that implementation works.
Any chance you could do a walk-though on creating a custom script about what does what?
Thanks
Chris
October 27th, 2005 at 1:56 am
Will this work with asp .net? I can’t use the standard validation that was supported on ASP .Net, so I have to look for other javascript validation control available out there. I tried implementing it, but it seems that the way ASP .Net submit the form is different with the standard one. Has anybody ever try it with ASP .Net yet?
Thank
Wendy
November 7th, 2005 at 7:37 am
Hello,
Excellent script. Though I found a small error. If I use the “-E” id to create a location to collect the error message - it does not work if the field has multiple validation -e.g. “required validate-integer” or you enter correct and incorrect data repeatedly. The fix was quite small:
Locate the two spots with the line:
if(fe) fe.parentNode.removeChild(fe);
and replace the line with the following code:
if (fe) {
while (fe.childNodes[0]) {
fe.removeChild(fe.childNodes[0]);
}
The problem was the script was removing the error nodes when the validation rules were met. However this meant that if there was a subsequent validation rule that had an error (require validate-integer) or there was an error on the subsequent sumission then the error place holder was gone and the error message appeared in the wrong spot.
}
December 9th, 2005 at 1:00 am
Wow, your validation is a dream come true. The JavaScript validation I’ve fought with for the last few years will gladly be rm’d.
One problem with the formatting. My non required fields look different than required fields, especially in Firefox. I’m using class=”" for non required fields. I’ve tried class=”none” and class=”none-required”. What am I missing?
Monte
December 9th, 2005 at 10:37 pm
Nevermind my last post. It was a conflict with another css stylesheet that was formatting the text inputs.
December 17th, 2005 at 4:29 pm
Hi, first of all let me thank you for your wonderful work!
Im currently trying to use wForms validation in my own project. Everything works smooth so far.
But i have encountered one serious problem with another script that i use, it’s called “Tab Pane” from the site http://webfx.eae.net/.
This script dynamically generates tabs from div elements.
Problem with wForms here is, that wForms validates only the fields on the visible tab, all other tabs are not validated.
Can anyone help me with this problem? Maybe there also is another recommendable “Tab Pane” script out there that will work fine with wForms.
Thank you for your help!
December 19th, 2005 at 9:37 am
Gianluca,
You should be able to force wForms to check non-visible field by adding the following code in your page (after the link to wForms.js)
wu.checkVisibility = function() { return true; };
December 19th, 2005 at 2:45 pm
Hi cedsav,
thanks four your quick help, doesnt work for me though ;(
I get a JS-error “wu not defined”.
?
December 19th, 2005 at 9:29 pm
Sorry instead of wu. use wf.utilities.
wf.utilities.checkVisibility = function() { return true; };
December 20th, 2005 at 2:06 pm
Thx works like a charm!
January 9th, 2006 at 3:44 am
Just want to thank you for this excellent toolset and making things that much less complicated for developers and non-developers alike. My complete and utter thanks for this wonderful code.
Best regards
January 24th, 2006 at 1:15 am
I am trying to add wforms to an existing site, but am having trouble. i added the js file link in the head and have added class declarations to all my input types including my submit class set to primaryAction. Please help?????
February 16th, 2006 at 3:05 am
I was using this tutorial which uses the built-in email validation of wForms, and noticed a problem. The validation allows spaces. You can test it on that guy’s site if you want to see it. I tried testing it on this page, and I’m not sure if it was confirmed or not, as clicking submit led to a 404 error.