Client-side Form Validation w/ jQuery… but with a lot of form inputs…
Probably the best example of form validation comes from Jeremy Keith’s DOM Scripting, which is probably the best book I’ve ever picked up. Ever since I read it a little over two years ago, it definitely got me into the loop as far as modern-day javascript is concerned… But anyway, he shows you how to create an unobtrusive way of doing form validation.
Basically all you gotta do is give the field you want to be required a class of “required”. Then in your javascript, you iterate through all the inputs and search for anything with a class of “required”. If the contents of that field are empty, then you put up an alert and stop the form from being submitted. I put my own little twist on it by coloring the border of the field red and alerting the user of how many fields need to be filled in. Since I’ve been a big fan of jQuery lately, i’ve re-done the function in jQuery…
Javascript:
$('form').submit(
function(){
$(this).find('.required').each(
function(){
if($(this).val().length < 1){
$(this).css('borderColor','#ff0000'); counter++;
} else {
$(this).css('borderColor','#ffffff'); } } ); if(counter > 0){ alert("There are "+counter+" fields that need to be completed."); return false; } } );
HTML:
Name*:
Email*:
Sorry the formatting sucks, but I haven’t figured out how to make things look nicely with this Wordpress Code Plugin. In any case, you can totally copy this exact function and use it for your purposes.
So this is pretty straightforward, but the only reason this function has come to my attention lately is because if you’re working on a webpage with oh…. 200+ input fields (i’ve got a page that looks like a spreadsheet), this function is RIDICULOUSLY slow in Internet Explorer 6 and 7. In fact, IE tells me “Are you sure you want to keep running this script?”. The reason it takes so long is that i’m using the class selector $(‘.required’) which actually goes through every single input and checks for the class “required”. It’s nowhere as fast as using the ID selector (an alias of document.getElementByID). So i dunno, I haven’t yet figured out a solution to this. I could definitely narrow down the fields that I’m going through but that seems kind of a hack. I want to be able to say “required” on any field I want to.
Without saying… it’s pretty clear how much faster my page with 200+ input fields performs on Firefox or Chrome… IE sucks. I should re-title my blog to the IE Sucks blog.
Pages: