How to validate form using Regular Expression in JavaScript ?

21 Sep, 2021
JavaScript is a scripting programming language that also helps in validating the user’s information. Have you ever heard about validating forms? Here comes into the picture JavaScript, the Scripting language which is used for validations and verification. To get deeper into this topic let us understand with examples.
Form Validation: Form validation is validating the values which are entered by the end-user during a form submission. For validating a form, Regular Expression plays a vital role. Let’s see what Regular Expression means.
Regular Expression: A Regular Expression is an object that describes a pattern of characters. Regular Expressions are used to perform pattern-matching and search-and-replace functions on text. So, in this area JavaScript plays a major role in validating the values. To, get more idea about the terminology let us see through an example.
Let’s understand how to validate forms using REGULAR EXPRESSION in JavaScript through examples.
 
Example 1: Form validation (validating an email)
Assume a registration form that contains the basic details of the end-users like Name, Phone number, Email id, and Address. When the user enters the email id without the domain name and “@” symbol the form turns out an error that says “domain name not included”. Ever wonder how this happens? This happens due to the Regular Expressions in JavaScript. Regular Expression can be defined as a stopper(pattern -match) to the values which are not correct i.e., “indicating an error while the end-user is entering the wrong details instead of the given regular expression “. Some of the characters used are “[abc],[^abc],\w,\W,\S”. Thus validating the email address entered by the end-user is done by JavaScript.
index.html
<!DOCTYPE html><html>  <head>    <title>creating mailing system</title>    <style>        legend {            display: block;            padding-left: 2px;            padding-right: 2px;            border: none;        }    </style>    <script type="text/javascript">        function validate() {              var user = document.getElementById("e").value;            var user2 = document.getElementById("e");            var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;            if (re.test(user)) {                alert("done");                return true;            }            else {                user2.style.border = "red solid 3px";                return false;            }        }    </script></head>  <body bgcolor="cyan">    <center>        <h1>Email Registration</h1>        <form>            <fieldset style="width:300px">                <legend>Registation Form</legend>                <table>                    <tr>                        <input type="text"                             placeholder="firstname"                             maxlength="10">                    </tr>                    <br><br>                    <tr>                        <input type="text"                             placeholder="lastname"                             maxlength="10">                    </tr>                    <br><br>                    <tr>                        <input type="email"                             placeholder="username@gmail.com" id="e">                    </tr>                    <br><br>                    <tr>                        <input type="password" placeholder="password">                    </tr>                    <br><br>                    <tr>                        <input type="password" placeholder="confirm">                    </tr>                    <br><br>                    <tr>                        <input type="text" placeholder="contact">                    </tr>                    <br><br>                    <tr>                        <label>Gender:</label>                        <select id="gender">                            <option value="male">male</option>                            <option value="female">female</option>                            <option value="others">others</option>                        </select>                    </tr>                    <br><br>                    <tr><input type="submit"                         onclick="validate()" value="create">                    </tr>                </table>            </fieldset>        </form>    </center></body>  </html>
Output:
This picture says a perfect email address is entered by the user, so the form is accepted and registration is done. When a person enters the wrong email the text box of the email is highlighted with red color border indicating it is an error.
Invalid email
Correct email and the form is submitted 
Example 2: Form Validation (validating phone number )
Suppose assume the same registration form. Ever wonder why the number should be started with only from 6, 7, 8, 9 and not the remaining numbers. Here, also the picture is played by Regular Expression which helps in validating one’s correct mobile number. Restricting the users to enter only 10 digits where the first digit should of numbers “6,7,8,9” and rest all digits can be of any number from 0-9 is done purely by regular expressions “[^6-9][,0-9]” which help in validating the forms whether the information entered is relevant to the pattern specified.
index.html
<!DOCTYPE html><html>  <head>    <style>        legend {            display: block;            padding-left: 2px;            padding-right: 2px;            border: none;        }    </style>      <script type="text/javascript">        function validate() {              var user = document.getElementById("c").value;            var user2 = document.getElementById("c");            var re = /^[7-9][0-9]{9}$/;            if (re.test(user)) {                alert("done");                return true;            }            else {                  user2.style.border = "red solid 3px";                return false;            }        }    </script></head>  <body bgcolor="cyan">    <center>        <h1>Email Registration</h1>        <form>            <fieldset style="width:300px">                <legend>Registation Form</legend>                <table>                    <tr>                        <input type="text"                             placeholder="firstname"                             maxlength="10">                    </tr>                    <br><br>                    <tr>                        <input type="text"                             placeholder="lastname"                             maxlength="10">                    </tr>                    <br><br>                    <tr>                        <input type="email"                             placeholder="username@gmail.com">                    </tr>                    <br><br>                    <tr>                        <input type="password"                             placeholder="password">                    </tr>                    <br><br>                    <tr>                        <input type="password"                             placeholder="confirm">                    </tr>                    <br><br>                    <tr>                        <input type="text"                             placeholder="contact" id="c">                    </tr>                    <br><br>                    <tr>                        <label>Gender:</label>                        <select id="gender">                            <option value="male">male</option>                            <option value="female">female</option>                            <option value="others">others</option>                        </select>                    </tr>                    <br><br>                    <tr>                        <input type="submit"                             onclick="validate()" value="create">                    </tr>                </table>            </fieldset>        </form>    </center></body>  </html>
Output:
This picture says a perfect phone number is entered by the user, so the form is accepted and registration is done. Upon entering the wrong phone number the text box of the phone number is highlighted with red color border indicating it is an error.
Correct contact and email so form is submitted 
Invalid email and Contact 
Thus, Validating a form can be done through JavaScript in the web pages. It should be tie up with  HTML which is a markup language. Although many other languages came into the picture for validations JavaScript is the basic way to learn how to understand the validations performed in the webpages. 
Blogathon-2021
CSS-Properties
HTML-Questions
HTML-Tags
JavaScript-Questions
Blogathon
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Connect Python with SQL Database?
Explain the purpose of render() in ReactJS
Data Mining - Cluster Analysis
How to build a basic CRUD app with Node.js and ReactJS ?
How to parse JSON Data into React Table Component ?
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form