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)

(required and alphabetic characters only)


(required and email values only)


(required, number only)


(not required, date format)


(required)

Your favorite color:

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:

  1. Enable the wForms extension by adding the following code to the <head> element of your page:
    <script type="text/javascript" src="wforms.js" ></script>
  2. 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"/>

  3. 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>
  4. 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 !

50 Responses to “wForms Input Validation Explained”

  1. Josh Says:

    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?

  2. Josh Says:

    Oops.

    Using: <input type=”text” name=”foo” class=”validate-alpha required”>

  3. cedsav Says:

    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).

  4. Omkar Says:

    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!!

  5. cedsav Says:

    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 ?

  6. Omkar Says:

    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.

  7. cedsav Says:

    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..

  8. Uffe Says:

    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 :)

  9. cedsav Says:

    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.

  10. Uffe Says:

    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 :)

  11. Eric Hobart Says:

    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

  12. Bojan Zivanovic Says:

    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 :D

  13. cedsav Says:

    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”

  14. cedsav Says:

    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.

  15. Bojan Zivanovic Says:

    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 :)

  16. cedsav Says:

    Bojan, I posted the code sample for a custom validation w/ field comparison on the wForms Customization page.

  17. Ben Says:

    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.

  18. cedsav Says:

    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” />

  19. Ben Says:

    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.

  20. Beate Says:

    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>

  21. fc Says:

    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.

  22. cedsav Says:

    fc, just add this to your CSS:

    .errMsg { display: none; }

  23. fc Says:

    thanks alot, thats exactly what i wanted to do.

  24. jace Says:

    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.

  25. jace Says:

    sorry, it seems the comment system removed the white spaces, so the sketch is useless…

  26. cedsav Says:

    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.

  27. Konstantin Says:

    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!

  28. jace Says:

    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.

  29. cedsav Says:

    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).

  30. Bryan Buchs Says:

    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?

  31. cedsav Says:

    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.

  32. Bryan Buchs Says:

    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…)

  33. cedsav Says:

    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

  34. Bryan Buchs Says:

    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

  35. Ralph Says:

    Can wforms do field validation on change (onchange)?

  36. cedsav Says:

    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).

  37. Ralph Says:

    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.

  38. Chris Says:

    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

  39. Wendy Says:

    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

  40. Amit Joshi Says:

    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.
    }

  41. Monte Persinger Says:

    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

  42. Monte Persinger Says:

    Nevermind my last post. It was a conflict with another css stylesheet that was formatting the text inputs.

  43. Gianluca Says:

    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!

  44. cedsav Says:

    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; };

  45. Gianluca Says:

    Hi cedsav,

    thanks four your quick help, doesnt work for me though ;(

    I get a JS-error “wu not defined”.

    ?

  46. cedsav Says:

    Sorry instead of wu. use wf.utilities.

    wf.utilities.checkVisibility = function() { return true; };

  47. Gianluca Says:

    Thx works like a charm!

  48. K Therriault Says:

    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

  49. jimmyK Says:

    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?????

  50. Tony Says:

    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.