JavaScript Form Validation Using Regular Expressions: Definitio…

Alexis Kypridemos

Web Developer
Technical Writer
CSS
HTML5
JavaScript

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, 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.

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 appearing here, 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 five numbers

We encourage copying this code appearing here 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.

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



View Video Only

26K views







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.

After the second forward slash, we can optionally include a modifier, like this one appearing here: /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







 








Partner With Alexis
View Services

More Projects by Alexis