Javascript Scripting Tutorial Part 3

Javascript Tutorial Regular Expressions, Form Validation and Event Handlers

Today I’m going to continue teaching you everything about Javascript. If you haven’t read my other Javascript tutorials they are available here:

You must read these tutorials before you have any hope of understanding the code that is coming. Like in the last tutorial I will teach you Javascript by walking you through a working script. As the title says above, this tutorial will focus on Regular Expressions, Form Validation and Event Handlers.

Regular Expressions

A Regular Expression is used to describe a series of characters, numbers and symbols. Regular expressions are used to verify that a visitor to your site entered a correct phone number or address. You would use a Regular Expression to state that the phone number:

  • Must contain at least 7 digits ex. 412.828.3200
  • It may have different symbols interspersed with these numbers ex. (412)-828-3200
  • It may be proceeded by an additional number. ex. 1-412.828.3200

An  example of a Regular Expression would be: /^\d{1,6}$/

What does this mean? Well, the forward slashs /, surround the regular expression. ^ signifies that the letters that proceed it will start the value you are looking for. \d{1,6}, signifies that you expect the user to type in between 1 and six digits. Then $ means that the value has ended.

I’ll teach you real world ways to use Regular Expressions with Javascript, if you are a bit confused. Don’t worry you’ll understand them after you practice with them. The program we will be working through today is located here. So on with the code:

<html>
<head>
<title>Javascript Tutorial Regular Expressions, Form Validation and Event Handlers</title>

<script type=”text/javascript”>

const pi = 3.14;

Here is the opening of the Javascript Script. I inserted the html, head, title and script tag. The script tag tells the browser that everything that proceeds it will be Javascript code and it needs to translate it properly.

In the previous article I didn’t show you how to create constant variables. A constant variable is a variable that you don’t want to change. I thought the constant pi, would be a good example. You just type in the keyword const, followed by the variable name and then give it a value.

function editNodeText(regex, input, helpId, helpMessage) {
// See if the visitor entered the right information
if (!regex.test(input)) {
// If the wrong information was entered, warn them
if (helpId != null)
helpId.appendChild(document.createTextNode(helpMessage));
// helpId.innerHTML = helpMessage;
return false;
}
else {
// If the right information was entered, clear the help message
if (helpId != null){

while (helpId.firstChild)
helpId.removeChild(helpId.firstChild);

}
return true;
}
}

If you didn’t read the last tutorial this will be extremely confusing. I’ll walk you through step-by-step:

function editNodeText(regex, input, helpId, helpMessage) {

Creates a function named editNodeText(). Anything surrounded by tags in an HTML file is called a node. With this function I’m going to change these nodes on the fly. The values sent to it include:

  • The Regular Expression I’m going to test for
  • The identification number associated with the node
  • The identification number for text I will be changing
  • The text I will be adding to a node

if (!regex.test(input)) {

Every Regular Expression includes a function that you use to check whether the chosen value meets its requirements. That function is called test. I’m asking function test, to check if the text located in the node with the id input is valid.

if (helpId != null)
helpId.appendChild(document.createTextNode(helpMessage));
return false;
}

If the text found in that node is not valid I check to see if the node I plan to paste helper text to is empty with : if (helpId != null)

If it is empty I place the helper message in that node with the appendChild function. The return function then notifies the javascript code that I’m done using this function and the curly brace } closes the if statement.

function resizeTheLogo(){
document.getElementById(“logo”).style.height=(document.body.clientHeight * 0.2);
}

This function will be called to dynamically change the height and width of an image. This is what is going on:

  • document.getElementById(“logo”) – Gets me an identification number for the node with the name logo
  • .style – Tells the browser that I’m about to change a CSS style for this node. I describe every CSS style in this tutorial.
  • .height – Tells the browser that I want to specifically change the height style
  • document.body.clientHeight * 0.2 – Tells the browser that I want it to get me the current height of the browser window and I want the image to have a height that is 20% of whatever the browser window is.

function isTheFieldEmpty(inputField, helpId) {
// See if the input value contains any text
return editNodeText(/.+/, inputField.value, helpId, “Please enter a value.”);
}

This function will be called to test if a text field node is empty. It accepts the variables inputField, which is the identification number for the node I’m checking for emptiness. (Not sure if that is a good word?) The other variable it is passed, is the identification number for the node I want to write in if the text field is empty.

return editNodeText(/.+/, inputField.value, helpId, “Please enter a value.”); sends a series of variables to the editNodeText function that you created above for testing.

Here you see your first Regular Expression: /.+/. It is requiring that the value contained in the text field be:

  • . – Any character, number or symbol
  • + – That there is one or more occurrences of the value that proceeds it

To put it simply, is the text box empty?

inputField.value – Is the id for the text field you want to check.

helpID – Is the id for the helper text node you may want to add helper text to

“Please enter a value.” – Is the message that will be displayed in the helper text node if no value is found.

function isAddressOk(inputField, helpId) {
// See if the input value contains any text
return editNodeText(/^\d{1,6}\s\w{3,16}\s\w{2,8}\w*$/, inputField.value, helpId, “Enter a Street (Ex.1234 Main St.)”);
}

This function is testing to see if the visitor entered a valid address. The Regular Expression /^\d{1,6}\s\w{3,16}\s\w{2,8}\w*$/ translates to:

  • ^\d{1,6} – The first value entered will be between 1 and 6 digits
  • \s – Then there will be a white space of any kind
  • \w{3,16} –  Then there will be a word that is between 3 and 16 characters in length
  • \s – Another white space
  • \w{2,8} – Another word between 2 and 8 characters long
  • \w*$ – It may or may not end with additonal characters of any type

You should now have a pretty good grasp on Regular Expressions, but I’ll teach you some more.

function isStateOk(inputField, helpId) {
// See if the input value contains any text
return editNodeText(/^A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY]$/, inputField.value, helpId, “Enter a State Code in Uppercase (Ex.NY, PA, CA)”);
}

Wow, this is a long Regular Expression, but what it’s doing is pretty simple. It is checking to see if the state code is valid. It is asking if the value entered starts with an A, C, D, F, G, H, I, K, L, M, N, O, P, R, S, T, U, V, or W? It is doing that by using the OR symbol |.

It is then asking, if it does start with one of those letters, is the letter that proceeds it one of the letters contained in the brackets []?

function isPhoneOk(inputField, helpId) {
// See if the input value contains any text
return editNodeText(/^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$/, inputField.value, helpId, “Enter a Phone Number (Ex.412-828-3000)”);
}

Here I’m checking for a valid telephone number. I’ll walk you through what’s going on here:

  • ? – Says to match zero or one occurrences of the item that proceeds it
  • [0-9] – Says to match any number between 0 and 9
  • ([0-9]( |-)?)? – Means you can consider the number valid if it starts with any number of numbers between 0 and 9 that are followed by the symbol -, but this is not a requirement. This covers if someone enters a international code, in their phone number, which isn’t common
  • (\(?[0-9]{3}\)? – Means the person can then enter 3 digits, using the numbers 0 through 9, but they don’t need to. This would be the area code.
  • |[0-9]{3})( |-)? – OR, if they didn’t enter those characters, it is ok to enter a three digit number between 0 and 9 and follow that with a -, or not. This would be the prefix of the number. Ex. If this is the number 828-3200, 828 would be the prefix
  • [0-9]{4} – Means you expect them to enter a four digit number, using the digits 0 through 9.
  • |[a-zA-Z0-9]{7})$/ – OR, if none of the other checks passed your tests, you will simply except 7 of any number or character, uppercase or lowercase.

Your almost a Regular Expression expert. Believe me, not many people can harness this powerful tool. You should be proud.

function isEmailOk(inputField, helpId) {
// See if the input value contains any text
return editNodeText(/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/, inputField.value, helpId, “Enter an Email (Ex. derekbanas@newthinktank.com)”);
}

For your last Regular Expression, we will check for a valid email address.

  • /^[A-Za-z0-9] – Means the email will start out with any number of numbers or letters, uppercase, or lowercase.
  • (([_\.\-]?[a-zA-Z0-9]+)*) – Then it is valid to use the symbols _, ., or – in the email address, or not because of the ?
  • @ – All of those characters will be followed by an @ sign
  • ([A-Za-z0-9]+) – The @ sign will be followed by one or more numbers or characters, uppercase or lowercase
  • (([\.\-]?[a-zA-Z0-9]+)*) – Then it is valid to use any ., -, number, or character, uppercase or lower, or not because of the *
  • \.([A-Za-z]{2,})$/ – The email address is expected to end with a period followed by two or more {2,} of any character uppercase or lowercase.

</script>
</head>

I’m very satisfied that you completely understand Regular Expressions now, so close the script and head tags and get ready to learn about more Event Handlers.

<body onload=”document.getElementById(‘name’).focus();” onunload=”alert(‘Please Don’t Leave’);” onresize=”resizeTheLogo();”>

Here we are defining three different event handlers.

  • onLoad: Will perform whatever action it is told, when the web page has loaded. In this case I’m telling the browser to place the users focus in the text box named ‘name’
  • onunload: Is an irritating Event Handler that will perform an action when the user tries to leave a web page. In this case, open an alert box with the message “Please Don’t Leave”
  • onresize: Performs a defined action when a visitor resizes the browser window. In this case it calls a function that will change the height and weight of a chosen image

<div>
<img id=”logo” src=”http://www.newthinktank.com/wp-content/uploads/2010/03/LittleBrain.png” alt=”Little Brain” onmouseover=”document.getElementById(‘logo’).src = ‘http://www.newthinktank.com/wp-content/uploads/2010/04/LittleBrain2.png’;”
onmouseout=”document.getElementById(‘logo’).src = ‘http://www.newthinktank.com/wp-content/uploads/2010/03/LittleBrain.png'”; />
</div>

Here I created a div that contains an image. I gave the image the identification code “id”. Told the browser where the image file is located with the src attribute. Then a set the Event Handler onmouseover, to change the image when the visitor moves their cursor over the image. Finally, I added another event handler onmouseout, that will change the image again when the visitor moves their mouse off of the image.

<div>
Click Button see an alert box:
<input id=”about” name=”about” type=”button” value=”Trigger Alert”
onclick=”alert(‘Your clicking my button’);” />
</div>

This code will fire an alert box when the visitor clicks on the button. I used the onclick event handler, which you may remember from the last Javascript article.

<div>
Enter your name:
<input id=”name” name=”name” type=”text” size=”30″
onblur=”isTheFieldEmpty(this, document.getElementById(‘name_help’))” />
<span id=”name_help”></span>
</div>

Here I use the onblur event handler. onblur triggers an action when a visitor leaves the chosen node. In this case, it calls the function isTheFieldEmpty() and asks it to make sure the visitor entered a value in the name text area. It passes a reference to the text area id and the id for the helper node.

I perform the same actions for the next five div’s so I won’t repeat my description on how they work.

<div>
Enter your street address:
<input id=”street” name=”street” type=”text” size=”30″
onblur=”isAddressOk(this, document.getElementById(‘street_help’))” />
<span id=”street_help”></span>
</div>

<div>
Enter your city:
<input id=”city” name=”city” type=”text” size=”30″
onblur=”isTheFieldEmpty(this, document.getElementById(‘city_help’))” />
<span id=”city_help”></span>
</div>

<div>
Enter your state code:
<input id=”state” name=”state” type=”text” size=”2″
onblur=”isStateOk(this, document.getElementById(‘state_help’))” />
<span id=”state_help”></span>
</div>

<div>
Enter your phone number:
<input id=”phone” name=”phone” type=”text” size=”15″
onblur=”isPhoneOk(this, document.getElementById(‘phone_help’))” />
<span id=”phone_help”></span>
</div>

<div>
Enter your email:
<input id=”email” name=”email” type=”text” size=”30″
onblur=”isEmailOk(this, document.getElementById(’email_help’))” />
<span id=”email_help”></span>
</div>

<div>
Click Button for a 3 Second Alarm:
<input id=”alarm” name=”alarm” type=”button” value=”Set Alarm”
onclick=”setTimeout(‘alert(\’3 seconds!\’)’,3000)” />
</div>

In the div above, when the user clicks the button an Event Handler called, setTimeout is triggered to perform a certain action after 3 seconds have ellapsed. The number 3000 is the number of milliseconds the browser should wait before springing into action. There are 1000 milliseconds in a second, if you wish to set up a different period of time.

</body>
</html>

Whee, we are done. You may not know it, but you know a ton about JavaScript after these 3 tutorials. All that is left to learn is Cookies, Object Oriented JavaScript, Error Catching, Graphics and a handful of useful built in functions. Soon you will be a Javascripting code warrior. If you have any questions leave them below.

Till next time…

2 Responses to “Javascript Scripting Tutorial Part 3”

  1. User says:

    I’m very thankful with your information on youtube. I decided to check out your website; however, the grey font with the white background on your tutorials is very hard to read. Honestly, it just made me wanna scroll all the way down hoping to find something of a different color.
    Just an observation.

    • Derek Banas says:

      You’re very welcome 🙂 When I set out to make a video game tutorial I knew the only way I could teach to make professional games I would need to teach how to program like a professional.

      My goal isn’t to teach you how to make one game, but instead I want to teach how to make any game. To do that you must understand object oriented design, refactoring, design patterns, design, drawing, math and more.

      I want you to understand what makes for a good game design. How to draw everything. How to program it so it can be extended. It won’t look like any game tutorial ever made, but it will also require you to study and practice if you truly want to make great games.

Trackbacks/Pingbacks

  1. Javascript Scripting Tutorial Built in Functions | new think tank - [...] : Look for a specific regular expression in a string. See my Javascript Regular Expression tutorial if you don’t…

Leave a Reply

Your email address will not be published.

Google+