• 20 hours
  • Easy

Free online content available in this course.

course.header.alt.is_certifying

Got it!

Last updated on 8/5/19

Use regular expressions

Log in or subscribe for free to enjoy all this course has to offer!

Our previous chapter's validation is quite basic. It only checks the presence of the @ sign, not where it is, which would actually confirm a valid email address format. Regular expressions allow for much greater precision with validation.

Regular expressions define a pattern to be sought in a string. Most programming languages allow the use of regular expressions. They're almost a language in and of themselves.  

The following content will be a little off-putting and hard to understand. Don't worry though. You don't need to learn regular expression syntax by heart and will only build them out when you actually have a use for them.

To start, let's try a regular expression to do the same thing as in our first @ example (where we used indexOf). Here's the associated JavaScript code:

var regex = /@/; // The string should contain an @ character
console.log(regex.test("")); // Will be false
console.log(regex.test("@")); // Will be true
console.log(regex.test("emily&mail.us")); // Will be false
console.log(regex.test("emily@mail.us")); // Will be true

You define a regular expression in JavaScript by placing its pattern between two / characters. The variable created from the regular expression is an object, and its test method detects the presence of the pattern in the string passed as a parameter. test returns true or false.

The following list shows some possible regex patterns.

Regex

Matches if

test() === true

test() === false

abc

The string contains "abc"

abc, abcdef, 123abc456

abdc, 1bca, adbc, ABC

[abc]

The string contains "a", or "b", or "c"

abc, daef, bbb, 12c34

def, xyz, 123456, BBB

[a-z]

The string contains any lowercase letter

abc, 12f43, _r_ 

123, ABC, _-_

[0-9] or \d

The string contains a number

123, ab4c, a56

abc

a.c

The string contains "a", followed by any character, followed by "c"

abc, acc, 12a.c34

ac, abbc, ABC

a\.c

The string contains "a.c"

a.c, a.cdef, 12a.c34

ac, abc

a.+c

The string contains "a", followed by one or more characters, followed by "c"

abc, abbc, 12a$ùc34

ac,bbc

a.*c

The string contains "a" followed by zero or more characters, followed by "c"

abc, abbc, ac

ABC, bbc

This leads us to the following conclusions:

  • Square brackets [ ] define a range of characters. Each string that has at least one character in the defined range will be a match. For example, the patterns [a-z] and [A-Z] let you research any letter of the alphabet, in lower or uppercase respectively.

  • Patterns [0-9] and \d let you search for digits.

  • The dot character . replaces any character.

  • The backslash character \ indicates that the character after it should be sought exactly as it's specified. For example, \. lets you look for the . character.

  • The site https://regex101.com lets you easily test regular expressions. Don't hesitate to use this resource to better understand regex!

Let's come back to the email address validation in our form. Among the numerous regular expressions we could use to perform this validation, let's use the following: /.+@.+\..+/.

Before going any further, try to decode the pattern and identify the conditions that a matching string would fulfill.

A string matching this check will:

  • Start with one or more characters (.+)

  • Next contain the @ sign (@)

  • Next have one or more characters (.+)

  • Next contain the . sign (\.)

  • Next have one or more characters (.+)

In other words, this string should be formatted as xxx@yyy.zzz. It still can't confirm a 100% valid address, but it's a more rigorous check than our first example!

Here's how to integrate this technique within our example form (you'd add this to the HTML's matching JavaScript file). Modify the blur event handler on the email address field:

// Validate the inputted email address
document.getElementById("emailAddress").addEventListener("blur", function (e) {
    // matches an xx@yyy.zzz format
    var emailRegex = /.+@.+\..+/;
    var emailAddressValidity = "";
    if (!emailRegex.test(e.target.value)) {
        emailAddressValidity = "Invalid address";
    }
    document.getElementById("emailHelp").textContent = emailAddressValidity;
});

Summary

  • You can use regular expressions to check that a string matches a specified pattern.

  • You don't need to memorize regular expressions. Only look up what you need to, when you need to.

Example of certificate of achievement
Example of certificate of achievement