Regular Expressions

Regular expressions are patterns used for matching and manipulating strings according to specified rules. We will be adding two regular expressions to our form one for our name field, and the other for an optional fieldset, that request the telephone number and date a user would like to be contacted. Before we begin analyzing our JavaScript code as per usual, well first dissect these regular expressions to gain a better understanding of how they work.


Name field pattern /^([A-Za-z ]{2,} )([A-Za-z]{2,})$/
All patterns must begin and end with a forward slash, the caret following the forward slash matches characters at the beginning of a string. Just as the dollar sign before the ending forward slash matches characters at the end of a string. The parentheses indicate a sub expression, think of them as individual components of a pattern. The brackets contain all characters that are allowed within the sub expression. Notice that only lower case/uppercase letters and a white space is allowed.

The curly braces containing the number two followed by a comma indicates that the sub expression must contain at least two characters. Keep in mind the sub expression ends with a blank space, signifying the first portion of our pattern must include a white space. Our second sub expression doesn’t contain a white space within its brackets nor is a white space present within the expression itself. We can interpret this pattern as a user having to enter their first name, followed by a space and ending with their last name. Such as "John Doe".

Phone field pattern /^(\([0-9]{3}\))([0-9]{3})(\-[0-9]{4})$/
Our phone pattern begins with and ends with the same few symbols as our previous pattern. However, notice the back slash, a back slash within a pattern indicates that the symbol which follows it should be included in the pattern, and not interpreted as part of the code for the pattern. The brackets for all three sub expressions allow only numbers between zero and nine. The curly braces for the first two sub expressions contains a number without a comma telling us that only three characters are permitted, while the curly braces for the last sub expression allows four. This pattern would translate to something along the lines of “(555)555-5555”.

Note that modern browsers perform their own pattern match validation for emails if the input type for that field is equal to email.


To incorporate the name field regular expression. We simply create a variable with the pattern as its value, and add it under the existing variables in our validatePersonalInfo() function.


function validateCPU() {
var fieldsetValidity = true;
var errorDiv = document.querySelectorAll("div.componentsErrorMessage");
var cpu = document.getElementsByName("CPU");
var namePattern = /^([A-Za-z ]{2,} )([A-Za-z]{2,})$/;
try {

We then create a new else if statement at the bottom of our validatePersonalInfo() function within the try block. That uses the .test method to see if our variables pattern matches the value of the input box, if the results of that match is equal to false. We throw a very specific error message to insure the user understands what input is allowed.


	else if (!(nameField.value)) {
	nameField.style.background = "rgb(255,233,233)";
	throw "Please Enter Your Name";}
	else if (namePattern.test(nameField.value) === false) {
	nameField.style.background = "rgb(255,233,233)";
	throw "Name must contain a-z/A-Z only and a space separator";}
	}

Note that you shouldn’t rely solely on your error messages to indicate a patterns structure, but also include succinct place holder text to give the user a chance to input the proper data type on their first attempt.


Above our validateForm(evt) function well add the final piece of code we need to validate our “Phone Appointment (Optional)” section. Since entering the following information is optional our form will not throw any errors if both fields are left blank. The first if statement checks if both field values are not equal to null, a second if statement which is nested within the first then executes. Testing our pattern against the phone input value. If input exists within one field, are last else if statement requires both fields to contain an entry.


function validateContact() {
var errorDiv = document.querySelectorAll("div.errorMessage");
var phone = document.getElementById("telephone")
var date = document.getElementById("tripDate")
var phonePattern = /^(\([0-9]{3}\))([0-9]{3})(\-[0-9]{4})$/;
try {
// reset styles to valid state
phone.style.background = "";
date.style.background = "";
errorDiv[2].style.display = "none";
if ((phone.value !== "" && date.value !== "")) {
// all fields are filled
	if (phonePattern.test(phone.value) === false) {
		phone.style.background = "rgb(255,233,233)";
		throw "Please use the exact format for phone field: (###)###-####";}
	}
	else if (!(phone.value === "" && date.value === "")) {
	// not all fields are blank
	throw "For Phone Appointment please fill both fields or leave both fields blank";}
	}
catch(msg) {
	if (phone.value === "") {phone.style.background = "rgb(255,233,233)";}
	else if (date.value === "") {date.style.background = "rgb(255,233,233)";}
	errorDiv[2].style.display = "block";
	errorDiv[2].innerHTML = msg;
	formValidity = false;
	}
}

All that’s left is to add the function to our call stack.


// add calls below to validation functions
validatePersonalInfo();
validateCPU();
validateGPU();
validateBrand();
validateStorage();
validateContact();

Take a swing at the form below to view our completed JavaScript Program in all its glory.


Note that upon form validation you will automatically be redirected to the results page.


Contact Us

Personal Info
Favorite Components CPU
Graphics Card
Preferred Manufacturer
Preferred Storage
Phone Appointment (Optional)
Sun Mon Tue Wed Thu Fri Sat

close

Countdown to appointment =

Additional Information