scriptygoddess

09 Feb, 2003

Javascript Validation

Posted by: Jennifer In: Lessons learned

It is usually recommended to do some javascript validation on a form before it's sent. This way, you don't have to waste server resources doing this. (It's still recommended to do some server side validation as well – but hopefully you can cut out some of the mistakes with the client side/javascript validation).

So, what I do is create one "validate()" function that goes through the form and checks each required field to make sure it has something filled in and checks to make sure email fields are contructed properly, etc. So it looks something like this:
function validate() {
//check a field to make sure it has something filled in
if(document.formName.textFieldName.value == '') {
alert('Please fill out textFieldName.');
document.formName.textFieldName.focus();
return false;
}
//offer the person the option of leaving a field blank
if(document.formName.textFieldName2.value == '') {
if(!confirm("Are you sure you want to leave this field blank?\n Hit 'ok' to continue, or hit 'cancel' to go back and make changes.")) {
return false;
}
}
// side note: the "\n" in the confirm window will make a new line
/*
if you're validating a FILE upload field - and want to make sure the extension matches what you expect, I create a function (look for it at the bottom) to check to make sure the file extension is correct
*/

if (!filterFileType(document.formName.fileUploadField, "gif")) {
/* the "!" in the line above means "not" so it reverses the value of whatever is next to it. So, since an "if" statement will only run if whatever in the () is true, we want to check to see if the file in the upload field ends with .gif - if it doesn't the filterFileType would return false - the "!" makes the statment "true" thereform the if statement runs the next line */
alert("Please submit .gif only type files");
document.formName.fileUploadField.focus();
return false;
}
//Get the value of which radio button is selected
// valRadioButton is a function I define below

var radioVal = valRadiobutton(document.formName.radioGroup);
//make sure that they actually selected one of the radio buttons:
if (radioVal == '') {
alert("Please select one of those radio buttons!");
return false;
}
//check email field (to make sure it's not blank)
if(document.formName.emailField.value == '') {
alert('You must enter in your email.');
document.formName.emailField.focus();
return false;
} else {
//Now check if email is valid
if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.formName.emailField.value))) {
alert("The email you entered is not a valid email address.");
document.formName.emailField.focus();
return false;
}
}
//if we made it this far - then everything must be filled out okay
return;
} // end validate functionfunction filterFileType(field, ext) {
if (field.value.indexOf('.' + ext) == -1) {
return false;
}
return true;
} // end function filterFileType
function valRadiobutton(radiobutton) {
myOption = -1;
for (i=0; i< radiobutton.length; i++) {
if (radiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
return "";
} else {
return radiobutton[myOption].value
}
} // end function valRadioButton

Just some info for the people who aren't up to speed on javascript – you'll see this type of line: document.formName.textFieldName.value throughout this script. Just a breakdown of what that line means, and where you'd have to customize it:
document – doesn't change. references the current document (html page)
formName – this does change. In your form tag, make sure you add somethingline name="formName" (where formName is whatever you name your form – can be almost anything).
textFieldName – this also changes. When you have a element in a form (ie, text field, text area, etc.) you'll also have a name="textFieldName" (again, where textFieldName is whatever you name the field)
value – this grabs the text that's been entered in (or whatever was prefilled). so this:

<input type="text" name="textfield" value="this is the text you see">

looks like this

So the last thing is, to get this validate stuff to run, you'll add this into your form tag:

onSubmit="return validate()"

12 Responses to "Javascript Validation"

1 | Arve Bersvendsen

February 9th, 2003 at 9:51 pm

Avatar

" This way, you don't have to waste server resources doing this. (It's still recommended to do some server side validation as well – but hopefully you can cut out some of the mistakes with the client side/javascript validation). "

This is wrong. All data sent from forms MUST ALWAYS be checked on the server side.

If you fail to check on the server side, a malicious visitor could hand craft input that is malicious to the server. Imagine if you only did client-side checking of the form I'm typing this in, and I submitted PHP code. PHP code I would use to hack, or break into the site.

Having said that; one can use client-side validation, as an _additional_ tool. A tool to give the user more immediate feedback if the data he/she is about to submit is ill-formed. But remember: As an addition, not a replacement.

</rant>

2 | Jennifer

February 9th, 2003 at 9:57 pm

Avatar

Hi Arve, take the claws down, please:
"It's still recommended to do some server side validation as well"
I agree with you. Aside from the malicious aspect you talk about – some companies turn off javascript on user's browsers as a default.

3 | Arve Bersvendsen

February 10th, 2003 at 12:37 am

Avatar

No claws. :-)

My point was(is) that the statement inside the paranthesis and the statement outside are (logically) contradictory.

And, at least from what I see from novice/intermediate web authors, they would interpret the combination of these two statements as "it's mostly ok to ignore server-side checking". I've seen this happen a number of times in newsgroup I frequent, and it's hard to explain to people why.

But I felt that it had to be clearified. I apologize for any scratchmark you unintentionally got from my claws.

4 | Jennifer

February 10th, 2003 at 8:04 am

Avatar

They're not contradictory, but maybe my point outside the parens was misunderstood. Here's a scenario:

Lazy form filler tries to fill out just one field where all fields are required – javascript catches each one and tells him "Sorry, dude – gotta fill out that field" "yup, AND that field" "YES! And that field too!!" – If you ONLY have server-side checking – then that's three trips to the server. Three trips to the server when it was possible to catch it with javascript – that is what I mean by a "waste of server resources".

My point in the beginning was check it with javascript then once again when the stuff gets to the server. (Not mentioned: in case (1) malicious stuff you talk about and/or (2) javascript turned off). "double"-checking the form data once on the server – that is NOT a waste of server resources.

Is that clearer?

5 | Jim Ley

February 10th, 2003 at 12:43 pm

Avatar

Don't over-validate !!

And make sure you don't validate incorrectly…

Your email:
if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test

Which appears to disallow + in the part before the @ and only allows @a.b.cc or @a.b.ccc and not @a.info or @a.b.c.d.e.f.g.h.museum or …

Over validating scares people away who might otherwise have spent some money or whatever…

6 | Jennifer

February 10th, 2003 at 2:46 pm

Avatar

Ok, I can see making it so that it will take .info or .museum (are those even "available" yet? I thought it was still in discussion) (also, what should that line be so that it would allow those?)

…but "+"? Is that even an allowed character for email? I didn't think it was…

7 | Jester

February 10th, 2003 at 6:24 pm

Avatar

The idea is to save resources, as Jen said, but javascript can easily be turned off so you must re-do the checks with PHP to make sure they don't get through. 99% of users (apparently) run with javascript enabled anyways, you just need to stop the idiots from trying to mess with your forms and such. Without proper checks users can manipulate file functions or inject into SQL queries (SQL injection vulnerabilites are a common newbie error).

Javascript is the quick solution but always back the filters up with something that can't be disabled.

8 | Jennifer

March 17th, 2003 at 2:14 pm

Avatar

One more validation here: I had a list of radio buttons – which it wasn't "required" to select one – but if you DID select a paricular one – then there was a sub list that WAS required.

For example:
How will you be arriving?
(_) car
(_) boat
(_) airplane
(_) flight 001
(_) flight 002

If you select "airplne" then you have to select which flight…

Here's the code that will validate the form is filled out correctly:

var airplaneChecked = false;
var flightChecked = false;
for (i=0; i<document.formName.transport.length; i++) {
if (document.formName.transport[i].checked && document.formName.transport[i].value == "airplane") {
airplaneChecked = true;
}
}
if (airplaneChecked) {
for (i=0; i<document.formName.flight.length; i++) {
if (document.formName.flight[i].checked) {
flightChecked = true;
}
}
}
if (!flightChecked && airplaneChecked) {
window.alert("Please select a flight.");
document.formName.flight[0].focus()
return false;
}

9 | Jennifer

August 13th, 2003 at 10:44 am

Avatar

One more addition – to simplify the checking of many fields to see that they're not empty, add the function:

function validRequired(formField,fieldLabel) {
var result = true;
if (formField.value == "") {
alert('Please enter your ' + fieldLabel +'.');
formField.focus();
result = false;
}
return result;
}

Then in the main validate function do this for each field you're checking:

if (!validRequired(formname.first_name,"first name")) {
return false;
}

10 | Anonymous

September 30th, 2003 at 3:39 pm

Avatar

Im trying to create a code using java script on a button, so when clicked it will check the current pages address and will take answer and depending on that will send it to one of two links
there are two address outcomes that the original search should come up with and two links it can go to. IM stumped on where to begin with this and how to get it to look at the web address.
any help would be greatly appreciated
Thanks
chinkley@hotmail.com

11 | Jennifer

February 10th, 2003 at 8:52 pm

Avatar

Ok. Here's a better email validation function that I found here and it seems to accept the .name and .info etc. (but it's not pretty!) 😉

<script language = "Javascript">
/**
* DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/
function echeck(str) {
var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(at,(lat+1))!=-1){
alert("Invalid E-mail ID")
return false
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(dot,(lat+2))==-1){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(" ")!=-1){
alert("Invalid E-mail ID")
return false
}
return true
}
</script>

So they're display of the validation function looks like this:

function ValidateForm(){
var emailID=document.frmSample.txtEmail
if ((emailID.value==null)||(emailID.value=="")){
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (echeck(emailID.value)==false){
emailID.value=""
emailID.focus()
return false
}
return true
}

12 | Jennifer

December 16th, 2003 at 11:43 am

Avatar

Another note to myself: I made another variation to the function above:

function validRequired(formField,fieldLabel,alertmsg)
{
var result = true;
if (formField.value == "")
{
if (alertmsg == "") {
alert('Please enter your ' + fieldLabel +'.');
} else {
alert(alertmsg);
}
formField.focus();
result = false;
}
return result;
}

And then it's called like this:
for using the "default" alert message:

if (!validRequired(formname.name,"name","")) {
return false;
}

or this way to put in a "custom" alert message:

if (!validRequired(formname.iLikePie,"","Please type in yes or no or whatever you want.")) {
return false;
}

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements