YUI Unobstrusive Javascript Validation

Ever since I started creating web forms, I have been implementing some sort of javascript validation. This often involved a fair bit of javascript attached to the onsubmit events of the forms. I was even using a Dreamweaver extension that did this for me!

I’ve since been shown the light, and tried some other javascript validation. One package gave me the idea for creating a method of providing validation using Class names on form elements, no messy javascript. Another package showed me more in depth how to accomplish it. But it was based on the Prototype library, and I would have to include that to my scripts (which is fairly large for such a simple task).

So I wanted to write my own. I wanted to apply class names to inputs, textareas, selects, checkboxes and radios and have the form validated without any javascript written into the html at all.

Just as a bit of technical stuff here, it was easy enough to add a listener to the form submissions, but not easy to stop the default action (ie, return false) to the form this way. A forum gave me advice to use the YUI library with it’s event handling to stop the event. And it works, yay! So I guess I too have a package to accompany my script, but the two files required are very small compared to the Protoype script.

How to use

It’s simple enough. In your page, reference the YUI library and event scripts (v0.12 are included in the package for you). Also reference the jsvalidation.js file, which will perform the checking.

Next, create your form. Try to be XHTML compliant, for all of us! Now depending on the type of form elemen you create:

  • text, password and textareas
    Add these classes to the element. You can add more than one class to an element, seperating them with a space. Don’t add two contradicting validations though.

    • required – Will make this field required. Reccomended to use with other classes too.
    • validate-number – Field contents must be a number
    • validate-digits – Field contents must be digits, but spaces are also allowed
    • validate-alpha – Field contents must be alphabetical characters only
    • validate-alphanum – Field contents can be alphbetical and numerical, no punctuation
    • validate-date – A valid javascript date value
    • validate-email – Field must be an email address
    • validate-url – Field must be a URL (including the http://)
    • validate-date-au – A valid date formatted as dd/mm/yyyy
    • validate-currency-dollar – A valid dollar value
  • select elements
    Add these classes to the select element. You can add both if you like.

    • validate-not-first – Make the user choose an option that is not the first on the list
    • validate-not-empty – Make the user choose an option that has a value that is not null
  • radio and checkboxes
    Add this class to only one of the options in a group of radio inputs or checkbox inputs.

    • validate-one-required – At least one checkbox/radio element must be selected in a group

Error messages are defined by adding the title attribute to the same element as the class name with validation. If no title has been specified for any of the failed elements, a friendly message will appear to hide your lazyness.

After validation

The script will check the form elements for valid entries, and apply an additional class name to the elements depending on the success or failure of the validation. For example:

  • text, textarea, password: Adds validation-passed on success, and validation-failed on failure
  • select elements: Adds validation-passed-sel on success, and validation-failed-sel on failure
  • radio and checkboxes: Adds validation-passed-cr on success, and validation-failed-cr on failure

The reason I created different classes for the types of elements is for the flexibility of the designer. You may want a red background for a failed text element, but not for a failed select element.

Also, a messagebox will be displayed with a list of defined error messages, or a simple message if no specific error messages were defined.

Features of the script

In addition to just form validation, this script is intuitive. It will not try to validate hidden fields, or even fields that are not clearly visible to the user (hidden by CSS properties).

I’ve also added a minimum length option to text, textarea and password fields. Similar to the maxlength attribute, you can insert a minlength=”x” attribute to these inputs.

This script is not a class. But merely functions. There are some dependancy functions it requires that I have written myself, including:

  • addClassName(element,class)
  • removeClassName(element,class)
  • isVisible(element)
  • string trimming functions

If you’re a javascript programmer, you may find these useful. The source is also included with the package.

Download and Preview

Update:
Version 2 has a few fixes and now includes a validate-regex class you can apply. This only applies to text fields, and requires a regex= attribute to be applied to the element.

Another Update:
A Prototype version of this script is now available (and it’s smaller!).

Technorati: yahoo, yui, javascript, validation, unobtrusive


Share this Post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Slashdot

Tags: , , , , ,

  1. written by Benjamin May 7th, 2007 at 01:09 | #1

    Thanks, I spent hours trying to find something as simple to implement as this, workt straight away :)


  2. written by Nick May 10th, 2007 at 07:29 | #2

    Great script set but I just installed this on our site and found hitting submit sometimes allows the form to go through with false checks?! Anyone this is sometimes quirky? IE 7 & FF 2.01 on WinXP Pro.


  3. written by jc May 10th, 2007 at 09:38 | #3

    Nope I haven’t found this yet. Perhaps there was a Javascript error when submitted? Or the class names were incorrect.


  4. written by Bryan May 19th, 2007 at 03:00 | #4

    The validation was working perfectly for me, but then apparently I broke something. I getting an error “waiter is not defined”. Do you have any idea what I may have done to cause that?


  5. written by Anthony May 19th, 2007 at 14:41 | #5

    Thanks for the script, a couple of suggestions though :)
    1. I don’t think you need different classes for different elements on failure. If someone wants different styles for select and input you could just use once class ‘fail’ and they could just put select.fail {…} and input.fail {…} to separate the styles.
    2. You probably already know this one, but it’d be good to encapsulate the whole thing so as not to muck up the global name space.


  6. written by jc May 21st, 2007 at 13:14 | #6

    The different classes for errors can be required, allow me to convince you:

    Text inputs and Radio/checkbox inputs both use the input tag – so it’s not possible to distiguish them using CSS (without the inclusion of other wrappers). So you might want a dotted border around the text inputs, but not around the radio inputs. Therefore the classes help there.


  7. written by jc May 21st, 2007 at 13:25 | #7

    bryan – waiter is a function I often use in my custom apps – and shouldn’t have made it’s way into this script..

    I’ve removed any references to it and you can download the fixed version from the link above.


  8. written by Jeff May 24th, 2007 at 05:22 | #8

    Great fill-in for a hole in YUI functionality.

    It appears to lock in display of validation errors as a javascript alert(). It would be much more useful to allow specifying a callback function to handle errors in whatever way the developer chooses (e.g. display an error block on the page, use a nicer looking popup layer, etc.)


  9. written by kevstelo June 11th, 2007 at 22:19 | #9

    I think I’ve read something simillar a few days ago. I don’t remember where, might have been on digg.com or slashdot.


  10. written by Joe June 15th, 2007 at 18:52 | #10

    Very nice script!
    I was wondering if it’d be easy to implement the checking of 2 fields being identical. Useful for a password confirmation.

    How could that be implemented?

    Thanks!


  11. written by Gopal Venkatesan June 24th, 2007 at 21:35 | #11

    Great Idea!
    Though I’m just wondering would it be nice to re-check the validation on typing for erroneous fields.


  12. written by jc June 28th, 2007 at 10:05 | #12

    I’m not quite sure what you mean there…


  13. written by Nick June 30th, 2007 at 01:42 | #13

    Even when I try the ziped example, clicking in the first field, hitting enter, clicking ‘ok’ to the alert, then enter again submits a blank form. On our try I thought this might be because of overlapping onloads? I’m not a JS expert but its a great idea.

    http://www.wpas-inc.com/wpas/contact/


  14. written by Angelo July 20th, 2007 at 02:28 | #14

    Hello,

    Will this validation script work when use it on a yui panel form?


  15. written by jc July 20th, 2007 at 08:52 | #15

    Umm, probably not. Since the script loads events when the page is loaded.

    The YUI panel form, if created at run time, is not available to this script. But, that said, it probably depends on the order in which the events are fired. There’s no harm in trying…


  16. written by astroloji July 29th, 2007 at 23:29 | #16

    really good blog


  17. written by Brad August 31st, 2007 at 05:38 | #17

    How would you implement a validation for a textfield that checks for alphas and a character like an apostrophe say in a person’s last name? Example: O’Sullivan

    Thanks


  18. written by jc August 31st, 2007 at 09:33 | #18

    hmm… validate-alpha is the closest class name u could you, but then it wouldn’t allow the apostrophe.

    I’ve updated the script to accommodate for this, now you can use validate-surname for the class name.


  19. written by Christo September 4th, 2007 at 00:54 | #19

    This is a really great script. Thanks!


  20. written by Brad September 27th, 2007 at 02:29 | #20

    JC, Thank you for your response to my question on 8/31. A strange thing is occuring and I can’t seem to find why the validation is allowing it. I’m using a class=”required validate-number” on a series of three textboxes, used for someone to input their phone number (ie xxx xxx xxxx). While doing some hardcaore testing of my work, I was able to pass validation by putting in “3e3″ in the text box of each. Somehow only this sequence of (number “e” number) passes. I don’t want to use the validate-digits since that allows for a space. Do you know why just an “e” in the middle of two numbers would pass validation? Any help would be great. Thanks again.


  21. written by Carlton Dickson October 4th, 2007 at 19:47 | #21

    Hey, the link to the zip file is down…maybe that got hacked too :(
    Thanks for the validation script by the way…very nice.


  22. written by Sundarram P.V. October 7th, 2007 at 21:41 | #22

    Hi,
    the script is very smooth.
    but I couldnt see the code behind, its in a minified form.
    the download of zip file link is broken
    do you have non-obfuscated version?


  23. written by jc October 8th, 2007 at 15:42 | #23

    Downloads are working again. Yet another setback of being hacked.


  24. written by Chris Hiester October 15th, 2007 at 12:14 | #24

    Nice job. I’m using this on a project and it works great. Thanks.


  25. written by Vijay Moses October 20th, 2007 at 00:28 | #25

    Great script !!! Thanks. Date validation doesnt seem to work for me – a 20/20/2007 is not caught. Am I missing anything here :-(


  26. written by Beanie Sigel January 15th, 2008 at 04:28 | #26

    YUI library is very powerful for web development. I use it for AJAX based scripts, but you showed me other thing i must use.
    Thanks a lot. :)


  27. written by Mus January 16th, 2008 at 05:33 | #27

    Hi this sounds like a good script I could really use right now. Does it do conditional validation checks too??


  28. written by Tim Middleton January 19th, 2008 at 02:58 | #28

    Me again. I also added the following a validator to allow me to define arbitrary regular expressions in the HTML code to match against using class “validate-regex”.

    Example:

    I inserted the following code on the line following “//search for validate-”:

    if (c.indexOf(‘ validate-regex ‘) != -1) {
    var r = RegExp(e.getAttribute(‘regex’));
    if (r && ! t.match(r)) {
    valid = false;
    }
    } else


  29. written by jc January 21st, 2008 at 13:48 | #29

    Sorry peeps, it’s taken a while to get your comments approved. You can blame spam bots.

    Beanie Girl: Using the YUI for this is primarily due to the event stopping features that it requires for the form. It can also be applied using Protoype (and I’ve converted it to, but haven’t shared yet).

    Mus: Conditional validation? Yes, it checks to see if the inputs contain the correct content. On the conidition it doesn’t, you get an error :)

    Tim: That sounds like a cool idea. If I release a version 2, that’s definately in there (with your name attached, of course)


  30. written by Richard February 11th, 2008 at 20:10 | #30

    I love it when I find something like this. Nice and easy to implement. does what it says on the tin.

    One thing: an alphanumeric search. What about “This search”. I know a space is not a alpha or a number but it’s still the sort of text you might want to let through in a search but validate-alphanum will fail it. I’ll stick Tim’s regex and use something like ^[a-zA-Z0-9]+$ for now.


  31. written by Richard February 11th, 2008 at 20:31 | #31

    Ooh, mind you, you need:

    var r = RegExp(e.getAttribute(‘regex’));
    if (r && ! t.replace(/ /,”).match(r)) {
    valid = false;
    }

    to get rid of those pesky start and trailing slashes… Otherwise, great workaround.


  32. written by Tyler February 15th, 2008 at 04:52 | #32

    I might not be the first to point this out. your script is calling a searchUp() function. It looks like this is supposed to by yui’s YAHOO.util.Dom.getAncestorByTagName(). I was getting problems submitting with hitting enter in the input fields. I just swapped it out for getAncestorByTagName() and it works fine.


  33. written by Tyler February 15th, 2008 at 06:29 | #33

    also, i wanted to only check the content of an input when it did not have a value. I added a “optional” check, so you can have a input with a class=”validate-alpha optional”. If the input has no value then let it pass:
    added this to the end of the big if/else structure:
    if(c.indexOf(‘ optional ‘)!=-1 && t == ”){valid = true}


  34. written by Joshua February 18th, 2008 at 20:02 | #34

    great! thanks.. its the function i’m looking for.. i still prefer the javascript validation than ajax style


  35. written by Joshua March 2nd, 2008 at 03:22 | #35

    there is bug when you hit enter in the form but its only happen in Firefox. i try on IE 6 and Safari this script is working fine. The bug is that the form is still submitted and not checked by validation class. When i try to debug with firebug, it says that SearchUp is not defined .. do you know how to solve this ?

    thx before


  36. written by jc March 4th, 2008 at 10:07 | #36

    I can’t believe that no-one has picked up on that bug yet. It seems the script is missing that function (and another one too). This has been fixed in version 2, you can download from the updated link in the article above.


  37. written by Marc March 6th, 2008 at 19:38 | #37

    Cool library. The only thing is that I find it a bit complex to use. But otherwise very nice work.
    I have myself also developed a validation library. The idear is that you do not have to use javascript to validate your form.

    check it out at http://www.wowww.nl/wordpress/?p=102


  38. written by Gunther Dippe March 10th, 2008 at 00:03 | #38

    Very nice indeed :-)
    Minor whish: It would also be nice to check the email address for leading and trailing spaces.
    Thanks mate for an excellent job!


  39. written by astroloji April 13th, 2008 at 05:52 | #39

    Cool library. The only thing is that I find it a bit complex to use. But otherwise very nice work.
    I have myself also developed a validation library. The idear is that you do not have to use javascript to validate your form.


  40. written by bcm April 23rd, 2008 at 15:44 | #40

    Good job! It’s very cool……


  41. written by prefabrik April 26th, 2008 at 06:08 | #41

    hey thanks for sharing good job keep it up


  42. written by Saqib Ansari June 4th, 2008 at 20:52 | #42

    I’ve modified this script. There was no option to validate only when the value exist in specified field otherwise ignore that field.

    Well nice script. Thanks


  43. written by Afnan Zari June 4th, 2008 at 21:07 | #43

    Saqib ansari …. Would you mind providing code for that fix !!! or is it copyrighted ~~~ (smile)


  44. written by prefabrik September 9th, 2008 at 21:46 | #44

    its very good projects.


  45. written by hekimboard September 17th, 2008 at 01:43 | #45

    thanks a lot.great!


  46. written by seenu September 23rd, 2008 at 21:01 | #46

    i was using one textbox in the date validate function. in this function only i enter some value in the text box only validate but another time is not validate how i solve it in java script


  47. written by creative September 26th, 2008 at 03:32 | #47

    How do I show error messages next to textbox rather than in alert? please help


  48. written by dış cephe September 28th, 2008 at 21:02 | #48

    wooww.great project.thanks.


  49. written by estetik October 3rd, 2008 at 21:26 | #49

    Great javascript. Can I use it with drupal?


  50. written by Meme buyutme October 4th, 2008 at 17:43 | #50

    Nice post about Unobstrusive Javascript Validation. Congrats.


Comment pages

Comments are closed.