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
- Preview the YUI based Validation script
- Download the YUI based Validation script (v2.0, 2008-03-04)
- Preview the Prototype based Validation script
- Download the Prototype based Validation script (v2.0, 2008-03-04)
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
Thanks, I spent hours trying to find something as simple to implement as this, workt straight away :)
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.
Nope I haven’t found this yet. Perhaps there was a Javascript error when submitted? Or the class names were incorrect.
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?
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.
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.
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.
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.)
I think I’ve read something simillar a few days ago. I don’t remember where, might have been on digg.com or slashdot.
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!
Great Idea!
Though I’m just wondering would it be nice to re-check the validation on typing for erroneous fields.
I’m not quite sure what you mean there…
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/
Hello,
Will this validation script work when use it on a yui panel form?
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…
really good blog
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
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.
This is a really great script. Thanks!
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.
Hey, the link to the zip file is down…maybe that got hacked too :(
Thanks for the validation script by the way…very nice.
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?
Downloads are working again. Yet another setback of being hacked.
Nice job. I’m using this on a project and it works great. Thanks.
Great script !!! Thanks. Date validation doesnt seem to work for me – a 20/20/2007 is not caught. Am I missing anything here :-(
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. :)
Hi this sounds like a good script I could really use right now. Does it do conditional validation checks too??
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
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)
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.
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.
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.
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}
great! thanks.. its the function i’m looking for.. i still prefer the javascript validation than ajax style
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
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.
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
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!
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.
Good job! It’s very cool……
hey thanks for sharing good job keep it up
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
Saqib ansari …. Would you mind providing code for that fix !!! or is it copyrighted ~~~ (smile)
its very good projects.
thanks a lot.great!
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
How do I show error messages next to textbox rather than in alert? please help
wooww.great project.thanks.
Great javascript. Can I use it with drupal?
Nice post about Unobstrusive Javascript Validation. Congrats.