Commenters

ah wei akmal annoymous iera Jay Rod josh Mike victor loya Vringo yumi :) 'triple N'

 

Latest Comments

 

Subscription

Subscribe to ChronoSight's feed now or get it right from your e-mail.

 

AJAX Form Validation

Posted by crynobone. on 27-May 2006. Filed under , and . View:14,714 Comment:14

Mr_el ask me on a few days back on how to create a generic form validation for AJAX. Everyone can create form validation but the key here is to make a generic version where the same form can be use again and again regardless what type of form you might be using. But however, this doesn't work with form to upload file.

In this tutorial I be using XHTML 1.1 compatible format where instead of using name I be using ID as form attribute. This going to make it a bit more difficult compared to normal method but I will explain later how to overcome it.

 

The Form

Let say you have a login form which require user to submit username and password. We going to assign the form id as login_user and both username and password input name attribute as user_name and user_password.

<form id='login_user' action='' onsubmit='ajaxvalidate(this); return false;'>
<label for='user_name'>Username:</label>
<input type='text' name='user_name' id='user_name' value='' size='40' alt='1' />
<label for='user_password'>Password:</label>
<input type='password' name='user_password' id='user_password' value='' size='40' alt='0' />
<input type='submit' name='login' value='Login' />
</form>

Validation Function

From the example above, we going to use a javascript function named ajaxvalidate() to make the validation. Let view the function line by line.

variable form_id here represent the form ID, it will hold a connection to each element inside the form. We need a variable to hold the form_id.elements as an object so form_id.elements will be pass into f_object.

var f_object = form_id.elements;

Now we need to make a loop to test each of the element inside form_id. There we are using alt as an id key to check whether the field is required or not. Here 1 marked as required while 0 as not. If it failed validate_fail() function will be called to display a notification.

for (var i=0; i < f_object.length; i++) {
if (f_object[i].name != '') {
if ( f_object[i].alt == 1) {
ret = validate_value(f_object[i]);
if(ret == false) return false;
}
// Copy & Paste AJAX parameters assign
}
}

Below is the part were you will assign name and value as an array so we can use it with XHTTPRequest. You can ignore this if you are merely using it for Javascript alone.

x = x +  "&";
if (f_object[i].type == 'checkbox' || f_object[i].type == 'radio'){
if(f_object[i].checked == true) val = f_object[i].value;
else val = 0;
}
else val = f_object[i].value;
x = x + f_object[i].name + "=" + amptrim(val);
Note: You will need amptrim() function to make it work

Complete code

The full code for ajaxvalidate().

function ajaxvalidate(form_id) {
var f_object = form_id.elements;
for (var i=0; i < f_object.length; i++ ) {
if (f_object[i].name != '') {
if ( f_object[i].alt == 1) {
ret = validate_value(f_object[i]);
if(ret == false) return false;
}
// Copy & Paste AJAX parameters assign
}
}
}

Alert Function

Lastly I will show you what inside validate_value() function.

function validate_value(y){
if(y.value==''){
alert('Please fill the following field!');
y.style.border = '2px solid #ff0000';
y.focus();
return false;
}
return true;
}

14 comments so far...

» twistermc@gmail.com:

on 26-July 2006 at 06:11 AM | Quote

I tried this code without the ajax bit and it failed. The script ran forever and never submitted. I tried to add in the ajax stuff and it kept not working. You should have downloadable files. Thanks

crynobone:

on 26-July 2006 at 10:10 AM | Quote

I tried this code without the ajax bit and it failed. The script ran forever and never submitted. I tried to add in the ajax stuff and it kept not working. You should have downloadable files. Thanks

Mainly because you missunderstood this as a form processing tutorial. This is just the part where the we generically validate each input value. You can use document.form[0].submit() or other formula to submit the form.
I tried copy-n-paste the tutorial just now an it work. Sorry no downloadable file cause I really want people who try the tutorial understand the concept rather than saving them time by copy-n-paste code everywhere in the internet.

» twistermc@gmail-nospam-please.com:

on 27-July 2006 at 02:47 AM | Quote

I understand the tutorial is on validating, but I'd like to make it work too. The submit line you provide above works, but the form throws a javascript error. "document.form[0].submit() is not a function"
So I either don't know where to put it, or I'm confused. I do appreciate all your help and for writing this, I just need to now tie it into something so it works.

crynobone:

on 27-July 2006 at 03:21 AM | Quote

I understand the tutorial is on validating, but I'd like to make it work too. The submit line you provide above works, but the form throws a javascript error. "document.form[0].submit() is not a function"


document.form[0].submit() is a command in javascript to submit a form without using a SUBMIT button (refer to Asynchronous File Upload with PHP, Javascript & iFrame where I show the usage of the command to submit the form upon file selection).

So I either don't know where to put it, or I'm confused. I do appreciate all your help and for writing this, I just need to now tie it into something so it works.


You can choose to add an temporary variable inside ajaxvalidate() function with default value equal to 1. If it ever hit alertuser() function the value will turn to 0. Before closing ajaxvalidate() function you can add an condition test where if the variable equal to 1 execute document.form[0].submit().

» twistermc@gmail-nospam-please.com:

on 04-August 2006 at 06:19 AM | Quote

Me again, it's not looping. It checks the first element and then it's good to go. Even in your example. It never checks the second or third or so fourth. I think I almost have it, really, I think I do.

crynobone:

on 04-August 2006 at 10:33 AM | Quote

Me again, it's not looping. It checks the first element and then it's good to go. Even in your example. It never checks the second or third or so fourth. I think I almost have it, really, I think I do.

Okay, to make the validation work with multiple element you need to add an attribute alt=1 (to force validate that particular element) or alt=0 (to ignore that particular element), refer to my form example.
The validation has a limiter where it would stop at current element where input are required, display an error and auto focus to that element.

» twistermc@gmail-nospam-please.com:

on 08-August 2006 at 23:01 PM | Quote

Yes, I did that. However, it still doesn't loop though more than just the first one. I have even re-done all the code, as listed above, changing the alt='0' to alt='1' in the password box. No validation happens to the password field though.

» twistermc@gmail-nospam-please.com:

on 08-August 2006 at 23:57 PM | Quote

Yea!! It works. Here was/is the issue. Above in the 'The full code for ajaxvalidate()' it says 'for (var i=0; i < f_object.length; i ) {' the end of that line is missing the plus signs after the i. Once I got that, it worked and stopped my never ending script issue I had at the very beginning. Thanks for the great code! I may re-post it if you allow me to.

crynobone:

on 09-August 2006 at 01:02 AM | Quote

Yea!! It works. Here was/is the issue. Above in the 'The full code for ajaxvalidate()' it says 'for (var i=0; i < f_object.length; i ) {' the end of that line is missing the plus signs after the i. Once I got that, it worked and stopped my never ending script issue I had at the very beginning. Thanks for the great code! I may re-post it if you allow me to.

I must had miss that part. It an old issue which this CMS had experience before because the AJAX Form Validation system (the same as this tutorial) which abandon + and & symbol from obtained from the form. I had noted this on All that happening around me (8).
function amptrim(str) {
s = new String(str);
s = s.replace(/&/g,"&");
s = s.replace(/+/g,"+");
return s;
}

» ChronoSight → AJAX Form Validation with savvy.js:

on 08-October 2006 at 16:18 PM | Quote

In the past I have share with you AJAX Form Validation, today I'm going to make the same task with less code using our Savvy.js JavaScript Library. We going to use className as an indication whether the input field is either required, string, num...

» Onimok:

on 27-July 2007 at 09:42 AM | Quote

Another waste of time! I am so tired of trying this stuff only to find that it doesn't work!!! If you are going to post a tutorial post all the files for download and make sure it works!!

crynobone:

on 27-July 2007 at 10:42 AM | Quote

Another waste of time! I am so tired of trying this stuff only to find that it doesn't work!!! If you are going to post a tutorial post all the files for download and make sure it works!!

I'm tired of entertaining lazy coders, the sample is already in copy-n-paste level and you just need to READ the whole thing. Remember, "No pain no gain..."

» pragard:

on 23-August 2007 at 13:14 PM | Quote

Hi...
I just want to ask you. What did you use on the "View Code" link.
Is it using Ajax too? Can you tell me how?
Sorry, I'm a newbie using Ajax.
Thanks.

crynobone:

on 25-August 2007 at 01:50 AM | Quote

Hi...
I just want to ask you. What did you use on the "View Code" link.
Is it using Ajax too? Can you tell me how?
Sorry, I'm a newbie using Ajax.
Thanks.

It's an application example made using Savvy.PItO object, you can read it at Inline Pop-up with Savvy.js.

Comment something...

Everything have a rules, so does our commenting:

  • * is required.
  • Don't provide any external links if you are posting for the first time!
  • Returning commentor can post total of 4 external links.
Name *
Website
Email *

Shout something...

Name
Website
Email