Home » JavaScript Tutorial

Regular Expressions in JavaScript

Here, we are going to learn about the Regular Expressions with Examples in the JavaScript.
Submitted by Siddhant Verma, on November 02, 2019

Regex is something very old and widely used today everywhere. It's an airtight security feature that helps you keep your database clean and saves the response time of the server when attached to frontend fields. They can surely seem intimidating at first, but understanding them will be a cakewalk by the end of this article. This article explains Regex from scratch. We'll also test some patterns directly and by the end create a simple form with regex validations on the frontend.

Okay, so what exactly are regular expressions?

They are expressions that help us check a series of characters for some 'matches'. Let's say you have an email id, it follows a certain pattern. For example, it has an '@' symbol and ends in a .com or .in extension. These patterns are what regex is used for. They are widely used in a lot of programming and database languages as well. They begin with '/' and end in '/' which means anything inside / / is a regular expression. So we have a basic syntax,

    / regex pattern /

Metacharacters

We use metacharacters to validate expressions. These characters have some special meaning in the regex. Some of them are,

FormatDescription
\d Match any digit characters between 0-9
\w Match any word character which includes a-z, A-Z, 0-9 and spaces
\s Match a whitespace character (spaces, tabs etc)
\t Match a tab character
d-- Matches the literal character 'd'
\d-- Matches any digit character

Special Characters

We also have some special characters for some special matches,

FormatDescription
+ One or more quantifier
\ The escape character
[ ] The character set
[ ^ ] The negate symbol in a character set
? Zero or one quantifier (Makes a preceding character optional)
. Any character barring the newline character
* Zero or more quantifier

General Syntax

We have already seen that our regular expression must lie between / /. The ^ symbol at the start means that our string must start with the character immediately after ^ and $ indicates the end of the string. Hence our general syntax for any regular expression becomes,

    /^ regex pattern $/

Alright now let's set up a form where we will add validations. If you're unfamiliar with forms and submit events in JavaScript, have a quick read here,

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Forms</title>
</head>
<style>
    form {
        margin: 20px auto;
        padding: 20px 20px;
        text-align: center;
        width: 400px;
        height: 400px;
        background: rgba(111, 146, 44, 0.514);
    }
    
    h2 {
        font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
        font-size: 40px;
        color: white;
    }
    
    input {
        background: white;
        border: 2px solid gainsboro;
        height: 30px;
        padding: 10px auto;
        margin: 10px auto;
        text-align: center;
    }
    
    input::placeholder {
        color: rgba(66, 151, 63, 0.61);
        text-transform: uppercase;
        letter-spacing: 3px;
        text-align: center;
    }
    
    input[type=submit] {
        border: 2px solid gainsboro;
        border-radius: 8px;
        cursor: pointer;
        background-color: rgb(97, 179, 138);
        color: whitesmoke;
        padding: 5px 5px;
        margin: 10px;
        text-transform: uppercase;
        box-shadow: 1px 1px 1px rgb(229, 233, 236);
    }
</style>

<body>
    <form action="">
        <h2>Form</h2>
        <input type="text" id="userName" placeholder="User Name">
        <br>
        <input type="email" id="Email" placeholder="Email">
        <br>
        <input type="password" id="password" placeholder="Password">
        <br>
        <input type="submit">
    </form>

</body>

We now have a basic form set up with three fields: user name, email and password. Should look something like this,

regular expression | example 1

Let's first try to figure out a simple regex pattern for each.

Let's say the username must have lowercase letters only and should be at least 6 letters long.

The regex pattern for the username will be: /^[a-z]{6,}$/.

The character set indicates that the user name must contain only those characters between a-z and the braces with {6,} indicates that it must be at least 6 characters long. Since the upper bound is not specified, we can have any number of characters as long as they're more than 6 characters long.

Let's figure out the pattern for email. We want the user to enter an email with an '@' symbol somewhere in between the email and should only end in a valid extension like .com, in, uk. A dot and anything after that can be an extension.

So the pattern for our email is: /^[^@][email protected][^\.]+\..+$/

We begin with anything but the '@' since our email must not begin with an @, then check for the '@' then we negate the '.' since we must have some domain name before our extension begins. The \ in between the regex is used to escape the sequence if it isn't a metacharacter or a special character.

Finally, let's break down the regex for the password. Our password should be between 8 to 15 characters long and must contain at least one uppercase, one lowercase, and one numeric digit.

Pattern for password: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/

The () evaluates regex searches separately so we can break down the pattern into 3 parts.

(?=.*\d) implies that the string must contain at least one numeric digit, (?=.*[a-z]) implies that the string must contain at least one lowercase character and (?=.*[A-Z]) denotes that the string must contain at least one uppercase character.

Alright, now we are done with the regex patterns. Let's see how we will implement validations using these in JavaScript.

HTML Pattern

The first method is to include the regex in the pattern attribute of our HTML tags of input fields. Here, we can use the inbuilt HTML pattern validation,

<form action="">
    <h2>Form</h2>
    <input type="text" pattern="/^[a-z]{6,}$/" id="userName" placeholder="User Name">
    <br>
    <input type="email" id="Email" pattern="/^[^@][email protected][^\.]+\..+$/" placeholder="Email">
    <br>
    <input type="password" id="password" pattern=" /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/" placeholder="Password">
    <br>
    <input type="submit">
</form>

Let's do it the other way now. Let's capture the patterns somewhere and check each input field if they match the pattern.

If we don't get a match we will append an error text to our HTML. For this, add the following to the styles,

.validationMsg {
    color: brown;
    font-size: 12px;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif
}

And include a p tag with a class validationMsg after the submit button in the form.

<p class="validationMsg"></p>

Now we'll do the matching in our submit event.

<script>
	const form=document.querySelector('form');
	const msg=document.querySelector('.validationMsg');

	form.addEventListener('submit',e=>{
	const usernamePattern=/^[a-z]{6,}$/;
	const emailPattern=/^[^@]+@[^\.]+\..+$/;
	const passwordPattern=/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/;
	e.preventDefault();
	if(!usernamePattern.test(form.userName.value)){
		msg.innerHTML+='Username must be at least 6 characters long all lowercase <br/>';
	}
	if(!emailPattern.test(form.Email.value)){
		msg.innerHTML+='Please enter a valid email <br/>'
	}
	if(!passwordPattern.test(form.password.value)){
		msg.innerHTML+='Password must contain at least one uppercase, one lowercase and one numeric value and must be 8 to 15 characters long <br/>'
	}
	})
</script>

We capture the form and the validation message to a variable. We store our regex patterns in different variables for every input field check if the pattern matches what the user typed in the field. If it does, we do nothing (maybe we get a response from the backend that reroutes the page) and if it doesn't, we show the error text underneath the submit button inside the form itself.

regular expression | example 2

Great! Our validations work fine. Test them out further with various combinations. You can refer to the full code here,

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Forms</title>
</head>
<style>
    form {
        margin: 20px auto;
        padding: 20px 20px;
        text-align: center;
        width: 400px;
        height: 400px;
        background: rgba(111, 146, 44, 0.514);
    }
    
    h2 {
        font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
        font-size: 40px;
        color: white;
    }
    
    input {
        background: white;
        border: 2px solid gainsboro;
        height: 30px;
        padding: 10px auto;
        margin: 10px auto;
        text-align: center;
    }
    
    input::placeholder {
        color: rgba(66, 151, 63, 0.61);
        text-transform: uppercase;
        letter-spacing: 3px;
        text-align: center;
    }
    
    input[type=submit] {
        border: 2px solid gainsboro;
        border-radius: 8px;
        cursor: pointer;
        background-color: rgb(97, 179, 138);
        color: whitesmoke;
        padding: 5px 5px;
        margin: 10px;
        text-transform: uppercase;
        box-shadow: 1px 1px 1px rgb(229, 233, 236);
    }
    
    .validationMsg {
        color: brown;
        font-size: 12px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif
    }
</style>

<body>
    <form action="">
        <h2>Form</h2>
        <!-- <span style="color:fuchsia;font-size:10px">Username must be at least 6 characters long with nly lowercase cahracters</span> -->
        <input type="text" id="userName" placeholder="User Name">

        <br>
        <input type="email" id="Email" placeholder="Email">
        <br>
        <input type="password" id="password" placeholder="Password">
        <br>
        <input type="submit">
        <p class="validationMsg"></p>
    </form>

</body>
<script>
    const form = document.querySelector('form');
    const msg = document.querySelector('.validationMsg');

    form.addEventListener('submit', e => {

        const usernamePattern = /^[a-z]{6,}$/;
        const emailPattern = /^[^@]+@[^\.]+\..+$/;
        const passwordPattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/;

        e.preventDefault();
        if (!usernamePattern.test(form.userName.value)) {
            msg.innerHTML += 'Username must be at least 6 characters long all lowercase <br/>';

        }
        if (!emailPattern.test(form.Email.value)) {
            msg.innerHTML += 'Please enter a valid email <br/>'
        }
        if (!passwordPattern.test(form.password.value)) {
            msg.innerHTML += 'Password must contain at least one uppercase, one lowercase and one numeric value and must be 8 to 15 characters long <br/>'
        }
    })
</script>

</html>





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.