Introduction

Recently, I posted a tutorial on degradable AJAX validation and a reader made a great comment about how the client-side JavaScript validation should have been done unobtrusively in order to separate the behavior layer from the form. And so I thought, “Sweet, I’ll just look that up and implement it.”

HTML Form Builder

Well, it turns out that the world of unobtrusive Javascript is a giant Pandora’s box of trouble. The biggest problem being : How do you inform the JavaScript (through clean markup alone) the different validation methods that need to be used on each field. In my obtrusive method, you can see that I’m passing information about whether a field is required or the type of information it contains through a function called validateMe on the event onblur.

<form name="form1" id="form1" method="post"     
action="formvalidation1.asp?validationtype=asp" onSubmit="return validate();"><input type="text" name="name" tabindex="1" id="name"  
onblur="validateMe(this.value, 'req_y/name', 'namemsg');"/>

If you’re into the whole separation of behavior and structure thing, you know that’s just ugly stuff up there. Now, we could just run a generic ‘attachevent’ like we do with image rollovers, but we wouldn’t be able to dynamically designate multiple types of validation for each field, which is a standard in today’s complex forms. Universal rules for validation on all inputs are just a bad idea and tends not to be reusable across projects. Sometimes you don’t want a certain field required, but still want to verify that a field is a properly formatted email address or what have you. What we want is JavaScript that’s flexible, clean and unobtrusive.

Lucky for you, I’ve gone and done most of the grunt work. Today, we’re going to go over working examples of three different types of unobtrusive JavaScript form validation. In addition to discussing the pros and cons of each validation method, I’ll give you code that’s ready to go and be plugged into your project. Nice, huh?

The Code

To follow along, you can download the examples here or see them in action below.

Use Hidden Fields

The first method comes from onlinetools.org and it uses hidden fields to hold the validation requirements. Now, I modified the script a bit to make it a little more versatile, but here’s what the markup would look like on a typical form:

<input type="hidden" name="required" id="required" 
value="name,emailaddress"  />
<input type="hidden" name="additional" id="additional" 
value="emailaddress/email,zipcode/zip" /><input type="text" name="name" tabindex="1" id="name" /><input type="text" name="zipcode" tabindex="2" id="zipcode" />
<input type="text" name="emailaddress" tabindex="2" id="emailaddress" />

In the example above, the the first hidden input field tells us that the values ‘name’ and ‘emailaddress’ are required according to the id. The second ‘emailaddress’ must be in valid email format and ‘zipcode’ must be in a valid zip format.

The first hidden field holds the required input ids separated by commas. The second hidden field is used to hold the validation information for those input fields that require additional validation besides requirement (ie. valid email or date). We pass this information to JavaScript by entering the id of the input followed by a forward slash (/) and then how we want to validate it.

My concern about this method is that while it does provide better markup, it just doesn’t seem very elegant. It’s confusing just trying to interpret what’s going on. Throw in a sizelimit=”100” and it’s even more taxing. Yes, this method is unobtrusive, but it doesn’t look like it scales very well (imagine what the hidden fields would look like on a large form with multiple validation types). This method gets bulky fast on large forms and seems prone to human errors.

Use the Class Atrribute

Another unobtrusive method uses the class attribute to hold our validation requirements. Here’s what the markup would look like:

<input type="text" name="name" tabindex="1" id="name" class="validate  required name namemsg"/>
<input type="text" name="nick" tabindex="2" id="nick" class="validate notrequired  none nickmsg"/>
<input type="text" name="email" tabindex="2" id="email" class="validate  required email emailmsg"/>

As you can see, it’s pretty easy to add multiple layers of validation to any input field. The JavaScript looks at the class name and finds its variables easily because they’re separated by spaces. This method is very human readable and easy to implement. Now, the JavaScript could get a bit large if a maxlength requirement were needed, but for the most part is pretty nice.

It works because W3C allows us to place multiple properties in a class attribute :

The class attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.

· 7.5.2 Element identifiers: the id and class attributes

One question we should ask ourselves, however, is if this is proper use of the class attribute? Does our page become confusing and lose some of its relevant meaning when some classes define how the page looks while other defines how it will act? Classes are usually associated with the presentation of a web page. In the above example, we are passing information on how we want the input box to behave.

If we look to the authority on this one, the W3C says to use classes with semantics in mind :

Think about why you want something to look a certain way, and not really about how it should look. Looks can always change, but the reasons for giving something a look stay the same.

· Use class with semantics in mind.

Good class names like ‘submenu’ or ‘warning’ describe the content . A bad class name, like ‘prettypinkbackground’, might not accurately describe the content when things need to be changed in the future (a div might not be pretty nor pink 3 months down the road). While ‘validate’ is not as bad as ‘prettypinkbackground’, is it appropriate? Who knows.

It’s a very nice method, but each developer should decide and evaluate whether this is an acceptable use of classes in their project.

Create your own Attributes and DTD

If you’re not into putting ‘validate required email’ in class names or hidden fields, you could go all hardcore and add your own custom attributes to the input fields and use a custom DTD to keep your page from not validating.

This idea was brought to light by Peter-Paul Koch on A List Apart and his Quirksmode web site.

The markup would look a little something like this.

<input type="text" name="name" tabindex="1" id="name" required="true" message="namemsg"/>
<input type="text" name="zipcode" tabindex="2" id="zipcode" validate="zip" message="zipcodemsg"/>
<input type="text" name="emailaddress" tabindex="2" id="emailaddress" required ="true" validate="email" message="email"/>

Now that’s a sexy looking form. No hidden fields and no fooling around in the classname. If a field is required we add required=”true”. If there is more validation to be performed we add ‘validate”typeofvalidation”. The message attribute tell us where the feedback will be displayed. Very easy to use, very easy to read.

To make it all validate I simply use the w3c DTD and added the following lines:

<!ATTLIST input required (true|false) #IMPLIED>
<!ATTLIST input validate (email|zip|phone|none) #IMPLIED>
<!ATTLIST input message (zipcodemsg|emailaddressmsg|namemsg) #IMPLIED>

We then attach our custom DTD to the web page at the top of the html document wit a simple doctype declaration.

<!DOCTYPE html SYSTEM "http://www.particletree.com/examples/unobtrusive-validation/dtd/xhtml1-custom.dtd">

Before you take the code and run, let’s learn a little more about what we’re doing above. A DTD or Document Type Definition is what you put at the top of your web pages to help the browser determine a list of legal elements that can be used on your page. It usually looks something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

The above DTD, for example, is what tells us that a <p> tag is valid but <newparagraph> is not. When your page run is through a validator, the code is checked against the page’s DTD. Since ‘required = “true”’ is an attribute we for inputs, the above DTD would not allow our markup to validate. By creating a custom DTD with new custom legal elements, we can say ‘required = “yes”’ or ‘validate = “zip”’.

Technically, though, you don’t need to change your DTD for this to work. The page will function just fine by adding custom elements and JavaScript can use ‘getAttribute()’ to access them just fine. We change the DTD because it’s not to have a page that validates, which happens to be a big fad I’ve noticed. To learn more about creating your own DTD there’s a good article about it on Alistapart.

Now, a custom DTD can be useful if you want to locate a problem during programming and an error occurs. If the page validates against a DTD (even if it’s yours) you can pinpoint the problem to the JavaScript and not have to worry that it’s an XHTML markup error. Because W3C recommends that you use the authoritative versions of these DTDs at their defined SYSTEM identifiers when validating content, custom DTD won’t validate according to the W3C Validator because they job is to create standards for us to abide by. You can see their list of legal dtd’s here. To check the validity of your page according to your doctype, you can use this validator at YoYo Design.

Unfortunately, there’s a dark side to all of this. Even thgough we’re technically allowed to create our own DTDs, doing so makes the web a very confusing place and if it got crazy would defeat the whole point having the w3c around to create standards for web development. Plus, the page is not totally future proof. Things could get ugly if a browser or W3C decided that ‘required=”true”’ actually means something different. If you’re curious about DTD’s and futureproofing you might want to look into namespaces.

When it comes down to it, there is no real right answer to which of the above methods works best. Personally, I prefer the class method of validation when it comes to my forms. The solution is a good balance on the issues and features I’m looking for and it’s very versatile. And I think the sacrifice to semantics is a bit trivial. Even though custom attributes and DTDs are appealing in their own rebellious, nerd-like fashion, creating a custom DTD just doesn’t sit right in my stomach, especially when I believe W3C works very hard to give me the valid tools I need to create a reusable and easy to use validation system.

Additional Information

The following articles and sites were great resources of information that lead to the creation of this guide.

HTML Form Builder
Chris Campbell

A Guide to Unobtrusive Javascript Validation by Chris Campbell

This entry was posted 5 years ago and was filed under Features.
Comments are currently closed.

· 59 Comments! ·

  1. Kevin Hale · 5 years ago

    Boy Chris, this is certainly a lengthy look at being unobtrusive… I’m impressed. I tend to agree with you that the class method is the best of the three. The hidden fields seem like they’ll just lead to piles of maintenance problems and the custom DTDs are certainly not working toward our ideal World o’ Web Standards. I think that was addressed in the A List Apart article on custom DTDs as well.

    Have you had a chance to put any of this into use yet on a site? I’d be interested to see what you whip up on a production site when you combine this with your AJAX wizardry.

  2. Chris Campbell · 5 years ago

    Thanks Kevin. Actually, I’m working on a project now that has about 200 input fields total. I haven’t put the ajax in but adding validation is much easier now using the class method. The best part is if someone takes over maintanence they won’t have a problem and I won’t have to explain much. After I make the ajax validation method unobtrusive I think I’ll play around with using that for validation. It will have to go through some testing to see how the server handles the load first.

  3. Relapse · 5 years ago

    Very interesting examination, however a stylistic question. As a coder, I get beaten over the head (and rightly so) by my more style/ accessibility savvy friends about the separation of Program, Markup (Semantic please), Presentation and Interactivity. Is utilising the Markup or Presentation layers to control Interactivity crossing the streams?

    Taking the above example. IDs are definitive keys for fields. Javascript validation is Interactivity, so wouldn’t the validation expressions be best set up in a head Javascript section — linking the IDs to set validation expressions (say a Javascript array, ID as key, and the fields of “Required”, “RegExp”.) On submit/ blur they are activated based on ID, with Presentation (class) changes to indicate validation errors as you suggest?

  4. Ryan Campbell · 5 years ago

    That’s a great idea assuming I understand you correctly. You’re suggesting that the validation info be stored in the javascript, and all that is needed to access that info is the ID of the field.

    The problem with that approach is that it eliminates the separation of code and content. In the methods listed in the article, any designer can come modify the form by adding fields or changing layout / validation, and the form will still “just work”. As a designer, they don’t need to know how or care how. If you move the validation info into the javascript, whenever a new field is added to the form, the javascript will need to be modified.

    Please correct me if I misunderstood what you were suggesting. There has got to be an ideal way of unobtrusive form validation, and it would be nice to find it out here :)

  5. Kevin Hale · 5 years ago

    Relapse, I actually thought the same thing about using ids to determine what validation methods are used (and I think Ryan’s point is relevant about the problems of needing to change code when additional fields are added).

    The above methods are good examples of systems that can be reused over and over again across projects and expanded easily by say the designer or even the programmer without having to rewrite new functions for each specific field’s requirements for validation.

    The initial time investment may be high for creating all the validation functions, but saves in the long run on future developments. And that initial investment is even lower because Chris got it started by providing some of the basic ones for us.

    So, kudos to Chris boy!

  6. Relapse · 5 years ago

    Ryan and Kevin: That’s precisely what I was suggesting, and well written. My English has been sacrificed for Perl and PHP methinks.

    The issue with the separation of code and content in the existing solutions is that the validation types still have to be specified in the Javascript anyway if a new form element is added. Say I add a URL field. I’ll have to create a URL validate section in the Javascript, so I’ll be editing the Javascript anyway. The perfect time to update the local Head section to link an ID with a validation type, and leave the functions themselves (or a raw RegExp handler) in an included Javascript.

  7. Relapse · 5 years ago

    A follow up.

    I should have specified that having Required as the Chris provided solutions works fantastically in terms of separation and functionality. A required field should be visually specified as required as a class, and having Javascript submit-validate inputs with that class as required makes perfect sense, taking advantage of the logical join of providing users with information and the supporting Javascript interactivity.

    The additional validations are specifying which Javascript functions to use to validate the field are where I have the mental issues above. You will need more validations, even with re-using an included Javascript for most pre-defined validation types. In fact, if taking the class route, if the included Javascript looks for class names then that interferes with new developers who may accidentally reuse an existing validation class field without knowing its attached validation code.

    The DTD solution requires off-page coding for new field types, and examing of the DTD to determine existing field types for new coders. So, coding that isn’t HTML or CSS is hard to avoid for Validation.

    There. Hopefully explained myself this time.

  8. Kevin Hale · 5 years ago

    “In fact, if taking the class route, if the included Javascript looks for class names then that interferes with new developers who may accidentally reuse an existing validation class field without knowing its attached validation code.”

    Couldn’t you tell the JS to use the validation functions to only work on classes specified in a specific id like “validateThisHereForm”? That way if a developer used a required class elsewhere, long as it didn’t sit inside that id, the other classes are shielded from being acted upon.

  9. Mislav · 5 years ago

    I think this whole class discussion has got way out of hand. W3C defined classes for us to be able to atach… well, a class or family name to an element. It is mainly used for presentation, but is that where it ends? Have we exausted all uses of a class simply with CSS?

    Imagine a XHTML document without any explicit presentation (CSS) or behaviour (JavaScript) layer containing a simple form. That form could have a form element, and it could be simple INPUT type=text element. Now, if that field was required, and I wanted to add semantics to my document, I would add the tag ‘required’ to the class attribute – it’s the only way to add semantics without tampering with the DTD. There, it’s now a clean and semantically rich document, and it already conveys information. Now I could expand this document with a presentation layer that says that all form fields of class ‘required’ should have red borders. Furthermore, I could add a behaviour layer to my document saying that all form fields of class ‘required’ should be checked before submit. I don’t see how one could even think of considering this dangerous practice; should we limit ourselves and the class attribute only for CSS? Did the W3C ever state that in their reccomendations?

  10. Relapse · 5 years ago

    Kevin: Yup, the “validate” class at the start of the provided class solutions provide that. However, if a user uses that identification class for something else… I know it’s a long shot, but I’ve seen long shots happen too often.

    Mislav: I agree with the class of required, I conceeded that point a bit earlier but not very eloquently. I probably have focused a bit much on classes in my comments. My main concern was with behavior attachments for the validation, and remaining unobtrusive without being obscurative.

    I have since taken Chris’ css solution and modified it to hopefully demonstrate what I meant by my comments

  11. Chris Campbell · 5 years ago

    Relapse, you’re right and you could do it using an ID but that could get complicated. For example EmailID = required/email/emailmsg or whatever on a page with a lot of input boxes would get ugly. Personally in my working situation casual updating may be done by someone other than me but nobody will be creating new classes. If someone needs a new form of validation they just need to give me a call and I’ll throw in the regex. So maybe sometimes I’ll get a call to add some type of new validation but that won’t happen often. If people are creating a generic form and want to add validation I want to provide them with the easiest and fastest method possible(keeping standards/semantics in mind). I guess it’s all situational to the amount of time you have and want to spend.

  12. Ryan Campbell · 5 years ago

    Just in case anyone could not find it, Relapse wrote his variation along with a brief explanation. Now that I have looked over it, I am trying to think of ways to combine the two.

    The goals are as follows: - Keep the markup as clean and accurate as possible - Have the ability to add another field to the form without touching the javascript

    With that in mind, here is what I have come up with. In the markup, have keywords for the ID of the field. For example, an email field could be called “workEmail” and another could be called “homeEmail.” In the javascript, just parse the ID for keywords. In this example, “email” would be a keyword. By parsing the ID, we would find the word “email” and validate it accordingly. You would have an array in you javascript of all possible keywords.

    So, if a designer wanted to add a couple of fields, they could go to the markup and add: input type=”text” id=”homePhone” class=”required” input type=”text” id=”workEmail”

    And that is all it would take – no need to touch the javascript. In addition, you can name the “error message display” node accordingly. For example, homeEmailMsg. That way the javascript can tack on “Msg” to the ID of the field to know where to display the message.

  13. steve · 5 years ago

    Chris,

    Great article. I’m right in the middle of a project that requires lots of form validation and your comments in this article as well as the one about ajax are very helpful.

    When you finishing implementing the ajax in the above solution, I was wondering if you were going to update your previous article about degradable validation?

    Thanks for all of your comments and code.

  14. Chris Campbell · 5 years ago

    Steve,

    Thanks, glad it helped. I will update the ajax validation using the class method most likely. Hopefully I’ll have it up sometime next week along with a couple other small improvements.

  15. Roger · 5 years ago

    Chris,

    Thanks for a good article. I’ve read about all three methods you mentioned, and all have drawbacks. I have the additional problem that I’m lazy, and i don’t like having to write validation logic both in javascript and on the server. I have been pondering using an xml snippet to hold the validation instructions and using it to run a ‘validation engine.’ The xml could be accessible on the client side by embedding it in the document, or calling it via ajax, and then parse it to add validation handlers to the appropriate form elements.

    Have you seen this done before? Do any major pitfalls come to mind?

  16. Chris Campbell · 5 years ago

    Roger,

    Trust me I know all about lazy when it comes to form validation . I saw an article at sitepoint using xml to perform the validation that looked promising. Perhaps it could be rigged up to validate server side. I also wrote an ajax form validation script that validates everything off of one server side page. One reader mentioned to use XSD but I’m honestly not knowledgeable enough to know the pros/cons of that method. Let me know if you come up with anything else since I’m always on the hunt for a better method of validation.

  17. Roger · 5 years ago

    Chris,

    Thank you for the links. After vacation this week I’ll try to put together an example of what I’m thinking.

  18. Craig · 5 years ago

    Great article.

    I’ve been pondering the same thing for a while and came up with a fourth solution: HTML comments…

    &lt!-validate:blur|ValidateString|please enter your name->

    My validation code recurses through the DOM looking for form elements with one or more comment siblings. It then parses the comment and defines appropriate events.

    The advantages: it’s totally unobtrusive, doesn’t change the original markup, is easy to use and extend, and validates properly.

    The disadvantages: it’s another syntax and IE5/5.5 don’t recognise comments as being part of the DOM.

    Whilst it works OK, I’m very tempted to use the class attribute instead.

  19. Kevin Hale · 5 years ago

    Craig, I think passing variables through comments is a totally wicked idea. Thanks for bringing that to the table.

  20. Camilo Duque · 5 years ago

    Hi, i’ve been using your examples for a practical work, but i have a little problem working with text inputs that the value are already pre stablished, in this cases your unobstructive validator doesn’t work too good and the only way that this work is rewriting the value manually. Have you any sugestions?¿solution?.IE

  21. Chris Campbell · 5 years ago

    Hi Camilo,

    So you’re saying the values inside the input boxes are already populated for the user. How’s the invalid info making its way into the form without the user? Someone had to enter the info at some time so how did it end up invalid? I would fix that first.

    You could validate everything when the page loads or onSubmit to catch problems with javascript. I would also recommend validating server side. The user won’t have real time feedback but nothing bad will make its way into the database (or wherever you send the info).

  22. Chris Campbell · 5 years ago

    Someone made another comment about this yesterday but we had a database problem that resulted in the loss of recent comments. There was nothing inappropriate, just an error (Thanks to Kevin).

  23. Philipp · 5 years ago

    Is there a way to validate textareas too?

  24. Chris Campbell · 5 years ago

    Phillip,

    Yes, you could check if the textarea is blank with similar code as seen in the examples. If there was a maximum length or some other requirement you could add that in the class, custom attribute, or hidden field.

  25. Michael Conger · 5 years ago

    Well done Chris. This solution is both straightforward and elegant. However, I must also recommend (to anyone who actually read the comments this far down) checking out qForms written by Dan Switzer.

    http://www.pengoworks.com/qforms

    This JS API for web forms has been around for several years and Dan’s just released a new major version. It is, perhaps even less obtrusive than your solution and it is INSANELY full featured and quite simple to use. Highly recommended.

  26. frequency decoder · 5 years ago

    bq. IE5/5.5 don’t recognise comments as being part of the DOM

    Is nice information to know as I have been pondering the unobtrusive form validation question recently and settled on embedding the validation rules as regular expressions wrapped within html comments - which was the only non-obtrusive way of using regular expressions that I could think of.

    A shaky “Sunday morning” attempt can be found here:

    http://www.frequency-decoder.com/form-validator/

    As I say, the test page is a first attempt, I’ve cleaned the code since (removing the ability to extend the validation Object prototype for instance) - actually, I must remember to post the updated code this weekend…

  27. George Jempty · 5 years ago

    I admit I haven’t delved into your examples but the buzz in the form of comments is encouraging and I will chip in my $0.02 regardless.

    How about a JSON expression that encapsulates all the form validation attributes? I think that would be highly unobtrusive.

  28. Bill · 5 years ago

    Personally, I don’t think adding a custom DTD is that bad of an option.

    Massimo at http://www.massimocorner.com/ posted his version of a DTD based validation library a few months ago and it is very very slick. Plus, his documentation is Top Notch!

    It can be found here: http://www.massimocorner.com/validator/index.htm

    I haven’t actually used it yet (as I rolled my own non DTD based unobtrusive JS solution in the past) but I am interested in giving it a try as I feel it is more robust.

    Heck, it is a good example of why we can define DTDs and why xHtml cam about in the first plac.e

  29. Scrambled · 5 years ago

    What about using Javascript to add the required=”true” to the id (using an array to hold the id’s) This would validate as the w3c test wouldnt load the Javascript therefore never seeing these? This doesnt bypass the scenario that this is added to a recommendation; but to me feels better than using the class for this. One reason is that its unlikely you’d have more than one element with the same class (the reason to have a class rather than id’s) with the same value leading to more markup in the css to style them all the same?

  30. nickg · 5 years ago

    I have been using something like this (client and server-side)

    Splitting the prefix for; . reqan = required alphanumeric . reqem = required email . etc…

    It’s clean and I am Happy :)

  31. nickg · 5 years ago

    I have been using something like this (client and server-side)

    (input type=”text” name=”reqan_name”) (input type=”text” name=”reqem_email”)

    Splitting the prefix for; . reqan = required alphanumeric . reqem = required email . etc…

    It’s clean and I am Happy :)

  32. hhh · 5 years ago

    Everyone needs a hug.

  33. Naomi · 5 years ago

    Sorry, this is probably a dumb question, new to javascript and now sure how to do this.

    In the second example that uses the class attributes, this just works for text fields, how can I modify this line in validate.js: var objInput = document.getElementsByTagName(‘input’);

    to work with a select box and textarea? I tried this: var objInput = document.getElementsByTagName(‘input,select,textarea’);

    but that didn’t work.

    Thanks for any help!

  34. Chris Campbell · 5 years ago

    There are no dumb questions Naomi. Actually there are but that isn’t one of them =p.

    You could store the select and textarea elements in their own arrays. For instance var objselect = document.getElementsByTagName(“select”)

    You could then run for loops for each element.

    That’s definitely not the most efficient way but should work and will at least get you started.

  35. Matthijs · 5 years ago

    Hi Chris, the link at the top (still) returns a 404. You might want to correct that. I emailed Kevin about it some time ago.

  36. Kevin Hale · 5 years ago

    Sorry, Matthijs. The link was an old reference leftover from when we were on textpattern. I added a permanent redirect on the .htacces to fix all the links that might be present throughout the site and to not break the ones referenced by others on other sites. If it doesn’t redirect immediately, try clearing your cache.

  37. Matthijs · 5 years ago

    Thanks Kevin. I already had a suspicion the link was supposed to point to degadable ajax validation.

    And, may I ask: what is your point of view of the best (unobtrusive) form validation routine at this moment, 6 months after publishing this article?

    The second ‘class’ approach appeals to me. I can expand the js to include more validation routines and reuse them easily. No inline js needed, and if client-side validation doesn’t work, server-side validation is still there.

    But maybe you have some new insights?

  38. Chris Campbell · 5 years ago

    Matthijs,

    We’re actually totally rewriting the way we handle validation using JavaScript and PHP classes. I’m hoping to write a new article on it in the next month or so. Although I preferred classes at first, using hidden fields is the approach we’re going with now.

    In the original example, if JavaScript was disabled, I hand coded the validation in PHP. For example, I had to know that email was validated as email and go into the PHP file and say “if $POST_[‘email’] is blank, validate it as email”. That approach is fine if you’re making a one time form for somebody and know some PHP.

    What we want now is a method so nobody ever has to go into a PHP file and hidden inputs allow us to do the trick. Hopefully I get some time to write up what we’re working on now because we believe it’s a better solution.

  39. Matthijs · 5 years ago

    Chris,

    that sounds very interesting.

    If I understand it a bit, you will make a kind of general class which has to receive certain kinds of input variables (from the normal and hidden fields) to be able to validate the input? So that even if javascript is (purposefully) disabled, validation takes place.

    Hmm, can’t wait to read more about it!

  40. Chris Campbell · 5 years ago

    Exactly.

    Whoever is designing the form will need to know the syntax to use for the hidden fields. It isn’t pretty but they’ll never have to touch php.

  41. Ben Vaughan · 5 years ago

    I’m looking into using your method for some validation, but I’m a bit stymied trying to validate radio, checkbox buttons and select menus.

    Any suggestions on how a fella could write this?

  42. Martin · 5 years ago

    Very interesting and beautiful site. It is a lot of helpful information. Thanks!

  43. 121sads · 5 years ago

    Everyone needs a hug.

  44. Baxter · 5 years ago

    It appears the once mighty ParticleTree is going down the abandoned-blog spam-comment black hole.

    As for semantic and unobtrusive ways of grabbing the required elements, why not just wrap them in a fieldset with the id or class of “required” “validate” or whatever. Then, just grab required.email, etc.

  45. cjvhf · 5 years ago

    Everyone needs a hug.

  46. X777 · 4 years ago

    How can Autofill be accommodated? Many people use autofill tools like the one included with the Google toolbar but doing so doesn’t trigger an onchange event. This means the form can be correctly filled in but fails validation as the attach() function is never run. Any ideas?

  47. gurava reddy · 4 years ago

    Everyone needs a hug.

  48. Sreenadh · 4 years ago

    Dear Chris, That was nice. Instead of using DTD and CSS class id, why can’t we use a server side xml configuration file? Let me state it clearly. Think of a situation where a HTML page/form is dynamically created by ASP/PHP based on an XML configuration file which defines the structure and validations for each field necessary for the page. The unobtrusive JS can read the configuration xml file using XMLHttp request and validate the auto generated (by ASP/PHP) HTML form based on that. If the form structure and validations changes what I would need to change would be only the XML configuration file stored in the server! Since the HTML form is auto generated by ASP/PHP based on this config file, I won’t have to change the code that generates the interface. Since the unobtrusive JS also uses the same config file via XMLHttp request, I won’t have to change that JS file as well! I think it would serve as a write once and use everywhere solution, as far as the JS file is concerned, and would be much useful in situations where the structure of the forms radically changes.

  49. Tom · 4 years ago

    Sent an e-mail off to Chris already, but if anyone has any ideas how to make this work (the class version, which I agree is best) with a phone number that is split up into 3 fields instead of one… so far I am striking out.

    I think the script is wonderful, so I’d like to get it to work for us. I’m required to break the phone up in 3 pieces too, I can’t make it one field. :/

    Thanks!

    Tom

  50. Sukumar · 4 years ago

    Everyone needs a hug.

  51. sdas · 4 years ago

    Everyone needs a hug.

  52. sala ree · 4 years ago

    Everyone needs a hug.

  53. 111 · 4 years ago

    Everyone needs a hug.

  54. kimberly · 4 years ago

    Everyone needs a hug.

  55. Subramanyam · 4 years ago

    Its really useful for me. I got lot of knowledge by your site.

    Here is my request that can you send me the validation scripts like 1. not allowing first character as spacebar in the textbox

    Thank You, Subramanyam

  56. gh · 4 years ago

    Everyone needs a hug.

  57. manjeet · 4 years ago

    I want how to validate Website url using javascript

  58. ultragc · 3 years ago

    Hey Chris,

    Nice work you have here. I am a newbie trying to play with javascript. I downloaded the sample code.

    Question. How do you include validation for dropdown box and radio buttons? Anyone?

    Thanks

  59. Phillip Smith · 3 years ago

    The sample links aren’t working at the moment…?