Skip to content
Related Articles

Related Articles

Form validation using HTML and JavaScript

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 30 May, 2022

Forms are used in webpages for the user to enter their required details that further send it to the server for processing. A form is also known as a web form or HTML form. Examples of form use are prevalent in e-commerce websites, online banking, online surveys to name a few. 

Syntax for form in HTML

HTML




<body>
        <h1 style="text-align: center;">REGISTRATION FORM</h1>
        <form name="RegForm" onsubmit="return GEEKFORGEEKS()" method="post">
             
<p>Name: <input type="text"
                            size="65" name="Name" /></p>
 
            <br />
             
<p>Address: <input type="text"
                            size="65" name="Address" />
        </p>
 
            <br />
             
<p>E-mail Address: <input type="text"
                            size="65" name="EMail" /></p>
 
            <br />
             
<p>Password: <input type="text"
                        size="65" name="Password" /></p>
 
            <br />
             
<p>Telephone: <input type="text"
                        size="65" name="Telephone" /></p>
 
            <br />
 
             
<p>
                SELECT YOUR COURSE
                <select type="text" value="" name="Subject">
                    <option>BTECH</option>
                    <option>BBA</option>
                    <option>BCA</option>
                    <option>B.COM</option>
                    <option>GEEKFORGEEKS</option>
                </select>
            </p>
 
            <br />
            <br />
             
<p>Comments: <textarea cols="55"
                            name="Comment"> </textarea></p>
 
             
<p>
                <input type="submit"
                    value="send" name="Submit" />
                <input type="reset"
                    value="Reset" name="Reset" />
            </p>
 
        </form>
    </body>

Validating a form: The data entered into a form needs to be in the right format and certain fields need to be filled in order to effectively use the submitted form. Username, password, contact information are some details that are mandatory in forms and thus need to be provided by the user.
Below is a code in HTML, CSS, and JavaScript to validate a form. 

HTML is used to create the form. 

JavaScript to validate the form. 

CSS to design the layout of the form.

Form validation:

JAVASCRIPT




<script>
            function GEEKFORGEEKS() {
                var name =
                    document.forms.RegForm.Name.value;
                var email =
                    document.forms.RegForm.EMail.value;
                var phone =
                    document.forms.RegForm.Telephone.value;
                var what =
                    document.forms.RegForm.Subject.value;
                var password =
                    document.forms.RegForm.Password.value;
                var address =
                    document.forms.RegForm.Address.value;
                var regEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;  //Javascript reGex for Email Validation.
                var regPhone=/^\d{10}$/;                                        // Javascript reGex for Phone Number validation.
                var regName = /\d+$/g;                                    // Javascript reGex for Name validation
 
                if (name == "" || regName.test(name)) {
                    window.alert("Please enter your name properly.");
                    name.focus();
                    return false;
                }
 
                if (address == "") {
                    window.alert("Please enter your address.");
                    address.focus();
                    return false;
                }
                 
                if (email == "" || !regEmail.test(email)) {
                    window.alert("Please enter a valid e-mail address.");
                    email.focus();
                    return false;
                }
                  
                if (password == "") {
                    alert("Please enter your password");
                    password.focus();
                    return false;
                }
 
                if(password.length <6){
                    alert("Password should be atleast 6 character long");
                    password.focus();
                    return false;
 
                }
                if (phone == "" || !regPhone.test(phone)) {
                    alert("Please enter valid phone number.");
                    phone.focus();
                    return false;
                }
 
                if (what.selectedIndex == -1) {
                    alert("Please enter your course.");
                    what.focus();
                    return false;
                }
 
                return true;
            }
        </script>

Styling the form:

CSS




<style>
        div {
            box-sizing: border-box;
            width: 100%;
            border: 100px solid black;
            float: left;
            align-content: center;
            align-items: center;
        }
 
        form {
            margin: 0 auto;
            width: 600px;
        }
</style>

COMBINED CODE [ALL OF THE ABOVE SECTIONS CLUBBED)

HTML




<html>
    <head>
        <script>
            function GEEKFORGEEKS() {
                var name =
                    document.forms.RegForm.Name.value;
                var email =
                    document.forms.RegForm.EMail.value;
                var phone =
                    document.forms.RegForm.Telephone.value;
                var what =
                    document.forms.RegForm.Subject.value;
                var password =
                    document.forms.RegForm.Password.value;
                var address =
                    document.forms.RegForm.Address.value;
                var regEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;  //Javascript reGex for Email Validation.
                var regPhone=/^\d{10}$/;                                        // Javascript reGex for Phone Number validation.
                var regName = /\d+$/g;                                    // Javascript reGex for Name validation
 
                if (name == "" || regName.test(name)) {
                    window.alert("Please enter your name properly.");
                    name.focus();
                    return false;
                }
 
                if (address == "") {
                    window.alert("Please enter your address.");
                    address.focus();
                    return false;
                }
                 
                if (email == "" || !regEmail.test(email)) {
                    window.alert("Please enter a valid e-mail address.");
                    email.focus();
                    return false;
                }
                  
                if (password == "") {
                    alert("Please enter your password");
                    password.focus();
                    return false;
                }
 
                if(password.length <6){
                    alert("Password should be atleast 6 character long");
                    password.focus();
                    return false;
 
                }
                if (phone == "" || !regPhone.test(phone)) {
                    alert("Please enter valid phone number.");
                    phone.focus();
                    return false;
                }
 
                if (what.selectedIndex == -1) {
                    alert("Please enter your course.");
                    what.focus();
                    return false;
                }
 
                return true;
            }
        </script>
 
        <style>
            div {
                box-sizing: border-box;
                width: 100%;
                border: 100px solid black;
                float: left;
                align-content: center;
                align-items: center;
            }
 
            form {
                margin: 0 auto;
                width: 600px;
            }
        </style>
    </head>
 
    <body>
        <h1 style="text-align: center;">REGISTRATION FORM</h1>
        <form name="RegForm" onsubmit="return GEEKFORGEEKS()" method="post">
             
<p>Name: <input type="text"
                            size="65" name="Name" /></p>
 
            <br />
             
<p>Address: <input type="text"
                            size="65" name="Address" />
        </p>
 
            <br />
             
<p>E-mail Address: <input type="text"
                            size="65" name="EMail" /></p>
 
            <br />
             
<p>Password: <input type="text"
                        size="65" name="Password" /></p>
 
            <br />
             
<p>Telephone: <input type="text"
                        size="65" name="Telephone" /></p>
 
            <br />
 
             
<p>
                SELECT YOUR COURSE
                <select type="text" value="" name="Subject">
                    <option>BTECH</option>
                    <option>BBA</option>
                    <option>BCA</option>
                    <option>B.COM</option>
                    <option>GEEKFORGEEKS</option>
                </select>
            </p>
 
            <br />
            <br />
             
<p>Comments: <textarea cols="55"
                            name="Comment"> </textarea></p>
 
             
<p>
                <input type="submit"
                    value="send" name="Submit" />
                <input type="reset"
                    value="Reset" name="Reset" />
            </p>
 
        </form>
    </body>
</html>

Validations used in above code snippets :

var regEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;                  //Javascript reGex for Email Validation.
var regPhone=/^\d{10}$/;                                                       // Javascript reGex for Phone Number validation.
var regName = /\d+$/g;                                                         // Javascript reGex for Name validation

Here we have used 3 Regular Expressions in Javascript for Email Validation, Phone Number Validation and User’s Name Validation.

  • regEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;

Above regular expression checks for valid mail-id entered by user.

\w shows any word character including Characters, Numbers and Underscore

+ Symbol shows one or more combination of characters.

Most common used special characters in mail-id’s are  Dot(.) ,Underscore(_) and (-) . Hence we have included them in \.- expression.

* Denotes Zero or more combinations of given characters.

$ Denotes End of the string or regular expression.

g denotes all matches from starting to end of given string with regular expression. g is used to find all the occurrences of the pattern instead of stopping after the first match.

  • regPhone=/^\d{10}$/;

In the Phone Number validation :

^ denotes starting of the string and it should be of type \d. That means it should contain only digits from 0 to 9. Any non-digit characters will not be accepted under \d.

{10} denotes that length of the Digit characters should be exactly 10 only. No extra or less characters will be permitted.

$ Denotes end of the string.

/ and / denotes start and end of the regular expression.

  • regName = /\d+$/g;  

Under user’s name validation :

User’s original name should not contain any kind of Numbers, Hence to avoid it we have used again \d class of characters which will accept only any combinations of 0-9 digits(Here + denotes one or more combination of any digits from 0 to 9). After that verification takes place using regName.test(name) .

Where “name” is the variable value entered by user in form’s name field. If it contains any kind of Digit value then it will prompt message of “Please enter your name properly.”

  • Validation on Password length :

If password entered by user is too small then browser should prompt message to user that password length is too small or like that .

Hence we have used this validation also in form field. If password entered by user have length less than 6 then browser will prompt message to user that “Password should be at least 6 character long”.

Please note that Regular_Expression.test(String) will check user entered string with the standard regular expression, 
If it matches then if condition will be satisfied and !Regular_Expression.test(String) will check for alternative condition.
  • Validation on Dropdown menu items :

If we have not selected any items from Drop-Down menu then it will prompt message that “Please enter your course”. Because (-1) denotes that not any field is selected and subsequent option items are considered as indices 0,1,2,3,4, and so on..

For indexing purposes .selectedIndex method is being used. If we are clicking on BTECH  then selectedIndex = 0, for BBA selectedIndex = 1 and so on..

And if user doesn’t select any option then by default it will take selectedIndex = (-1) and it should not occur . Hence what.selectedIndex == (-1) is used in If condition.

Validation Check for Above Form :

 

 

 

 

 

Resulting Form:

Reference : 
https://en.wikipedia.org/wiki/Form_(HTML)

HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!