JavaScript Form Validation Using Regular Expressions: Definition & Example

Instructor: Alexis Kypridemos

Alexis is a technical writer for an IT company and has worked in publishing as a writer, editor and web designer. He has a BA in Communication.

In this lesson, you'll learn what regular expressions are in computer programming. You'll see how to validate form input in JavaScript through examples of the search() and match() methods.

Regular Expressions

Regular expressions, also known as regex or regexp for short, are patterns of ordinary and special characters used in computer programming to search text for words, single characters or more obscure patterns.

RegEx and JavaScript

While regex can be used in your JavaScript code for a number of reasons, probably the most frequent reason will be to check the input users enter through forms.

For example, you may want to make sure that users enter a valid email address correctly in a sign-up form, complete with @ sign and a domain, like .com, before sending their input to a server-side program for processing.

In the code example below, we'll check two simpler cases in a web form:

  • a name input, which should contain only letters
  • a zip (post) code input, which should contain 5 numbers

We encourage copying this code into an online JavaScript editor or saving it as a .html file and viewing it in a web browser to see the JavaScript in action.

<!DOCTYPE html>
<html>
<body>
<form onsubmit="regEx(); return false">
Name:<br/>
<input type="text" /><br/>
<br/>
Post/ZIP code (5 digits):<br/>
<input type="text" /><br/>
<br/>
<input type="submit" />
</form>
<script>
function regEx(){
function testName(){
var name = document.getElementsByTagName("input")[0].value;
var nameTest = name.search(/[a-zA-Z]/g);
if (nameTest == -1||name == ""){
alert("Please enter only letters in this field.");
}
}
function testZip(){
var zip = document.getElementsByTagName("input")[1].value;
var zipTest = zip.match(/\d/g);
if (zipTest.length != 5||zip == ""){
alert("Please enter 5 numbers in this field.");
}
}
testName();
testZip();
}
</script>
</body>
</html>

In the code above, the form in the HTML is pretty standard, with two text inputs and a submit button. The fun part starts in the JavaScript segment, inside the <script> element. Before we get into details of what the JavaScript does with its regex, let's mention this will be triggered when the user presses the ''Submit'' button. This is determined in the following line of code:

<form onsubmit="regEx(); return false">

Now, to the JavaScript. All the commands are contained in one function, regEx(), triggered in the manner described above. The regEx() function in turn includes two smaller functions, testName() and testZip().

Each of these functions checks one of the form inputs. Both functions are built following the same approach. Let's start with the first function, testName().

This function's first task is to get the value the user entered in the ''name'~` input and store it in the variable name with this line:

var name = document.getElementsByTagName("input")[0].value;

Next, the function checks if the value entered contains letters. This is where the regular expression comes into play. Let's look at the line of code first, then break it down in detail to understand how it works:

var nameTest = name.search(/[a-zA-Z]/g);

First off, we create the nameTest variable to store the result of our regular expression test.

The search() Method

We set up our regex test with the search() method, which is a regular expression method. We use this syntax: name.search(). Inside the parentheses we place the actual regex, i.e. what to look for. In this case, the regex is: /[a-zA-Z]/g

RegEx Syntax and Modifiers

All regular expressions in JavaScript are placed between two forward slashes, like so: /your regex/.

The expression in this case is: [a-zA-Z]. The brackets and hyphen denote a range of characters. For example, [a-z] denotes all lower case letters. [A-Z] represents all upper case letters. And [a-zA-Z] represents all lower and upper case letters.

Brackets without the hyphen represent only a group of characters, and not a range. For example, [az] would instruct the search to find any occurrence of the letters a or z, and no other letter.

For a comprehensive reference of JavaScript regex syntax, see this page from W3 Schools: https://www.w3schools.com/jsref/jsref_obj_regexp.asp

After the second forward slash, we can optionally include a modifier, like this: /your regex/modifier.

A regex modifier is a character that instructs the search to do something it would not do by default. In this example, our modifier is g, which stands for global, and instructs the search to find all matches of the expression. If we did not include the g modifier, the search would find only the first match.

The search() method returns the value 0 if it finds the term it's looking for, and -1 if it does not.

To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 160 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create An Account
Support