Monday, November 11, 2024

Javascript Basics Part 3

This is the third in a 10-part series that will introduce you to the JavaScript language.

In the last article, we covered if/else statements, some basic validation and functions. To try out the script we wrote in that article, you can click here. If you don’t fully understand any of these concepts, you should read (or re-read) the last article.

It’s great that we now know how to validate data, but when you are writing your javascript you generally won’t need to validate the number of imaginary apples left, will you? One of the most common areas of javascript usage is on form fields. Let’s say you have a simple contact form for example. You might want to make sure the user has entered their name on the form, or that they have selected an at least one radio button for a question. Here is an example of such a form:

First Name: Your Favorite Color: Blue
Red
Green
Yellow
Black
Other
Last Name:
Email Address:

We are going to be using this form extensively throughout this article, so if you would like you can click the “Lock This Form In Place” button and the form will always be visible on your screen.

The first step in validating our form is learning how to create a javascript object that refers to the form. All of the forms on your page can be referenced with “document.forms”. If you have a form named “tutform”, you would access it as “document.forms.tutform”.

All of the elements inside of that form (input boxes, select boxes, checkboxes, etc) are referenced with “elements”: “document.form.formName.elements”. If there is an input field on a form called “firstname”, you could display the value of this field:

alert('First Name: ' + document.forms.tutform.elements.firstname.value);

If you click the above button and then submit the tutorial form, you will notice that you get an alert with whatever value is in the “First Name” box. How is this accomplished? When you submit a form, your web browser looks for “onsubmit” code. If this code exists, your form runs it before submitting:

<SCRIPT TYPE="text/javascript">
function validateForm(){
// your form validation code goes here
}
</SCRIPT>

<FORM ONSUBMIT="return validateForm();">
<!-- your form elements go here -->
</FORM>

Now that we know how to access a form and the elements in that form, we will begin with some basic validation. A common task is to make sure that your users enter a value into whatever input box you have. For example, you want to make sure that your user enters their name.

As you may have noticed in the previous snippet of code, you can use the “.value” property on a form object to get its value. This works for any type of form object. So we now want to check and make sure that the user enters both a first and last name on our form:

function validateForm(){
	var form_object = document.forms.tutform;
		if(form_object.elements.firstname.value == ''){
		alert('You must enter your first name!');
		return false;
	} else if(form_object.elements.lastname.value == ''){
		alert('You must enter your last name!');
		return false;
	}
	return true;
}

The important lines to note in this function are the “return false;” and “return true;” lines. If your validation function returns a value of “true”, the form will submit as normal. If, however, it returns a value of “false”, your form will not submit. It is up to you to tell the user why it does not submit, hence the alerts that we put into our function.

Looking at our demo form, another important field to validate would be the “Favorite Color” radio buttons. If you click a few of these buttons you should notice that only one of them can be selected at any one time. It would be nice, however, to make sure that our user selects at least one of these buttons.

Radio buttons and checkboxes on forms present a unique situation. You will often have several radio inputs with the same name, something that is almost always avoided with input boxes, select boxes, etc:

<input type="radio" name="color" value="blue">Blue
<input type="radio" name="color" value="red">Red
<input type="radio" name="color" value="green">Green

Because of this, there is a way to access all radio buttons with the same name. “document.forms.formName.elements.radioName” will contain a list with each radio button in it. Since we need to make sure at least one radio button is checked, we need to loop through every one of these radio buttons. If at least one of them is checked, our validation function should return true. So our validation function is now:

function validateForm(){
	var radios = document.forms.tutform.elements.color;
	for(var i=0; i<radios.length; i++){
		if(radios[i].checked) return true;
	}
	alert('You must select a color!');
	return false;
}

The new element in this code is what we call a “for loop”. It looks a lot more complicated than it actually is, so let’s break it down:

for(var i=0; i<radios.length; i++){

There are three values inside of the parenthesis, each one separated by a semi-colon. These values, separated out, are:

var i=0

i<radios.length

i++

The first value is simply where we set a variable. You should understand this with no problem by now. The second value is a test condition. Our for loop will continue to run as long as this test condition returns “true”. If it ever returns “false”, the for loop stops and the next line continues. So what “i<radios.length” is saying is that our for loop should continue to run as long as our variable i is less than the number of radio buttons we have.

“length” in this case is a property of an array. We have not gotten into arrays yet but to simplify things, “radios.length” simply returns the number of items in “radios” which is, in this case, 6 since we have 6 radio buttons.

The final value of our for loop, “i++” is code that should be run after each increment of the loop.

Attempting to put this into english, our for loop does the following:

  1. Set i equal to 0.
  2. Test to see if i is less than radios.length, which is 6.
  3. If this is true, execute the code in the for loop.
  4. After the code in our for loop executes, add 1 to our i variable.
  5. Go to step 2 until “i<radios.length” fails. This will fail after the 6th loop when i=6.

There is one other type of loop that we will cover now, which is a “while loop”. The following code does exactly the same thing as our for loop above:

var i=0;
while(i<radios.length){
	if(radios[i].checked) return true;
	i++;
}
alert('You must select a color!');
return false;

You might have already noticed that we have the exact 3 same snippets of code in our while loop that we had in our for loop: “var i=0”, “i<radios.length” and “i++”. The only difference is the position in which they occur. With a while loop, only the check, “i<radios.length”, is any different from anything you have written before. This check goes into the parenthesis immediately following “while”. We initialize our variable(s) before the while loop, and we increment i, “i++”, inside of our loop.

Going back to our loops, there is one thing left to explain: “if(radios[i].checked)”. Our radio’s variable contains an array of radio buttons with the name “color”. We will cover arrays in our next article, but here is a simplified explanation: radios[0] returns the first radio button. radio[1] returns the second, radio[2] the third, etc. up to radio[5] which returns the 6th button. If we had more radio buttons, 100 for example, radio[99] would access the 100th radio button.

All these numbers might seem off to you. Why does radio[5] access the 6th radio button? Well in javascript, as in many other programming languages, a lot of things start with the number 0 instead of 1. This is just one of those cases, but you will see it repeatedly. So 0 is actually the first element, 1 is the second and so-on.

There is one thing left to validate on our form–the e-mail input. This is actually a fairly complicated field to validate and doing it properly is beyond what we are going to be teaching today, but we will do some basic validation. What should we do? Well we know that any e-mail address has to contain one, and only one, @ character. It also has to contain at least one period following the @ character (the period seperating the domain from the TLD, ie “webreference.com”).

function validateForm(){
	var email = document.forms.tutform.elements.email.value;
	if(email.indexOf('@')<0){
		alert('There must be an @ sign in your e-mail address');
		return false;
	} else if(email.indexOf('@') != email.lastIndexOf('@')){
		alert('There can not be more than one @ sign in your e-mail address');
		return false;
	} else if(email.indexOf('.')<0){
		alert('There must be at least one period in your e-mail address');
		return false;
	} else if(email.lastIndexOf('.')<email.indexOf('@')){
		alert('There must be at least one period following your @ sign in your e-mail address');
		return false;
	}
	return true;
}

There are two new, similiar, functions in this code that we need to explain. “indexOf” returns a number containing the position of one string in another string. ‘abcdef’.indexOf(‘a’) will return 0 (once again 0 means the first position). ‘abcdef’.indexOf(‘cdef’) will return 2, and ‘abcdef’.indexOf(‘aaa’) will return -1. -1 means that the string was not found. In many instances, -1 is what is returned if a function fails.

Similiar to this, “lastIndexOf” returns the position of the last occurance of one string in another. ‘abcba’.lastIndexOf(‘a’) will return 4, whereas ‘abcba’.indexOf(‘a’) will return 0.

So looking at our code, our first if statement makes sure there is at least one ‘@’ sign in our e-mail address. If there wasn’t an @ sign, email.indexOf(‘@’) would return -1 and the if statement would fail.

The next statement combines indexOf and lastIndexOf. If there is more than one @ sign in our e-mail address, these two functions will return different values, as in our ‘abcba’ example above. If there is only one @ sign, these two functions will return the same value. So we check to see if they are not equal to each other.

The third statement is basically identical to the first one, except it checks for a ‘.’ instead of an ‘@’.

Finally, the fourth if statement checks to see that we have at least one period following the @ sign in our e-mail address.

The downside to this method is that the simple string “@.” would pass this validation. It should be apparent that this is not a valid e-mail address. There is another method to check an e-mail address, and to check many other things. This is done with what is called a “Regular Expression”. Although we will not explain regular expressions here, we will show an example of e-mail validation and leave it as an exercise for you to do more research if you want.

function validateForm(){
	var email = document.forms.tutform.elements.email.value;
	if(!(/^[a-zA-Z][w.-]*[a-zA-Z0-9]@[a-zA-Z0-9][w.-]*[a-zA-Z0-9].[a-zA-Z][a-zA-Z.]*[a-zA-Z]$/.test(email))){
		alert('Please enter a valid e-mail address');
		return false;
	}
	return true;
}

As you can see, using a regular expression results in much shorter (and much more robust) validation code, but it is also a lot more complicated!

Taking all of the examples in this article, we can now make one function to validate our entire form:

function tut7(){
	var form_object = document.forms.tutform;
	var radios      = document.forms.tutform.elements.color;
	var email       = document.forms.tutform.elements.email.value;

	if(form_object.elements.firstname.value == ''){
		alert('You must enter your first name!');
		return false();
	} else if(form_object.elements.lastname.value == ''){
		alert('You must enter your last name!');
		return false();
	} else if(email.indexOf('@')<0){
		alert('There must be an @ sign in your e-mail address');
		return false();
	} else if(email.indexOf('@') != email.lastIndexOf('@')){
		alert('There can not be more than one @ sign in your e-mail address');
		return false();
	} else if(email.indexOf('.')<0){
		alert('There must be at least one period in your e-mail address');
		return false();
	} else if(email.lastIndexOf('.')<email.indexOf('@')){
		alert('There must be at least one period following your @ sign in your e-mail address');
		return false();
	}

	for(var i=0; i<radios.length; i++){
		if(radios[i].checked) return true();
	}
	alert('You must select a color!');

	return false;
}

Join us next week when we continue with our JavaScript Primer series with a discussion of arrays!

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured