• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • JS Introduction
  • JS Getting Started
  • JS Syntax
  • JS Variables
  • JS Generating Output
  • JS Data Types
  • JS Operators
  • JS Events
  • JS Strings
  • JS Numbers
  • JS If Else
  • JS Switch Case
  • JS Arrays
  • JS Sorting Arrays
  • JS Loops
  • JS Functions
  • JS Objects
  • JS DOM Nodes
  • JS DOM Selectors
  • JS DOM Styling
  • JS DOM Get Set Attributes
  • JS DOM Manipulation
  • JS DOM Navigation
  • JS Window
  • JS Screen
  • JS Location
  • JS History
  • JS Navigator
  • JS Dialog Boxes
  • JS Timers
  • JS Date and Time
  • JS Math Operations
  • JS Type Conversions
  • JS Event Listeners
  • JS Event Propagation
  • JS Borrowing Methods
  • JS Hoisting Behavior
  • JS Closures
  • JS Strict Mode
  • JS JSON Parsing
  • JS Error Handling
  • JS Regular Expressions
  • JS Form Validation
  • JS Cookies
  • JS AJAX Requests
  • JS ES6 Features
Home >> javascript >> JS Form validation

JS Form validation

For the past decades, web forms have become an essential part of web applications. It is mostly used to collect users' data such as name, email address, location, age, and so on. However, it is actually possible that some users might not enter the data you've expected. So the need to save bandwidth and avoid unnecessary strain on your server resources you can validate the form data on the client-side (i.e user's system) using JavaScript before passing it onto the web server for further processing.

The client-side validation most times helps create a better user experience since it is faster because validation occurs within the user's web browser, while server-side validation occurs on the server, which requires the user's input to be first submitted and sent to the server before validation occurs. Also, the user has to wait for the server's response to know what exactly went wrong.

The subsequent sections will enable us to take a closer look at how to perform JavaScript form validation and handle any input errors found.

Note: The client-side validation is never a substitute or alternative for server-side validation. Therefore, you are advised to always validate form data on the server-side even when they are already validated on the client-side, as users can disable JavaScript in their browser.

 

Form Validation with JavaScript

In this case, the form validation process consists of two parts i.e. the required fields validation which is performed to ensure that all the mandatory fields are filled in, and the data format validation which is performed to ensure that the type and format of the data entered in the form are valid.

The example below will show us how this actually works.

 

Creating the HTML Form

You can create a simple HTML form that we will validate on the client-side using JavaScript when the user clicks on the submit button. however, we shall create an HTML file named ‘application-form.html’ and place the following code in it, then save it somewhere on our system.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Simple HTML Form</title>
    <link rel="stylesheet" href="style.css">
    <script src="validator.js"></script>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()" action="confirmation.php" method="post">
    <h2>Application Form</h2>
    <div class="row">
        <label>Full Name</label>
        <input type="text" name="name">
        <div class="error" id="nameErr"></div>
    </div>
    <div class="row">
        <label>Email Address</label>
        <input type="text" name="email">
        <div class="error" id="emailErr"></div>
    </div>
    <div class="row">
        <label>Mobile Number</label>
        <input type="text" name="mobile" maxlength="10">
        <div class="error" id="mobileErr"></div>
    </div>
    <div class="row">
        <label>Country</label>
        <select name="country">
            <option>Select</option>
            <option>Australia</option>
            <option>India</option>
            <option>United States</option>
            <option>United Kingdom</option>
        </select> 
        <div class="error" id="countryErr"></div>
    </div>
    <div class="row">
        <label>Gender</label>
        <div class="form-inline">
            <label><input type="radio" name="gender" value="male"> Male</label>
            <label><input type="radio" name="gender" value="female"> Female</label> 
        </div>
        <div class="error" id="genderErr"></div>
    </div>
    <div class="row">
        <label>Hobbies <i>(Optional)</i></label>
        <div class="form-inline">
            <label><input type="checkbox" name="hobbies[]" value="sports"> Sports</label>
            <label><input type="checkbox" name="hobbies[]" value="movies"> Movies</label>
            <label><input type="checkbox" name="hobbies[]" value="music"> Music</label>  
        </div>
    </div>        
    <div class="row">
        <input type="submit" value="Submit">
    </div>
</form>
</body>
</html>

 

Building the Form Validation Script

Here we are going to create a JavaScript file that holds our complete validation script.

So, we shall create a JavaScript file named ‘validator.js’ and place the following code inside it, then save it at the same location where we saved the previous HTML file. Please, carefully check through each line of the following example code to understand how JavaScript validation works:

// Defining a function to display error message
function printError(elemId, hintMsg) {
    document.getElementById(elemId).innerHTML = hintMsg;
}

// Defining a function to validate form 
function validateForm() {
    // Retrieving the values of form elements 
    var name = document.contactForm.name.value;
    var email = document.contactForm.email.value;
    var mobile = document.contactForm.mobile.value;
    var country = document.contactForm.country.value;
    var gender = document.contactForm.gender.value;
    var hobbies = [];
    var checkboxes = document.getElementsByName("hobbies[]");
    for(var i=0; i < checkboxes.length; i++) {
        if(checkboxes[i].checked) {
            // Populate hobbies array with selected values
            hobbies.push(checkboxes[i].value);
        }
    }
    
	// Defining error variables with a default value
    var nameErr = emailErr = mobileErr = countryErr = genderErr = true;
    
    // Validate name
    if(name == "") {
        printError("nameErr", "Please enter your name");
    } else {
        var regex = /^[a-zA-Zs]+$/;                
        if(regex.test(name) === false) {
            printError("nameErr", "Please enter a valid name");
        } else {
            printError("nameErr", "");
            nameErr = false;
        }
    }
    
    // Validate email address
    if(email == "") {
        printError("emailErr", "Please enter your email address");
    } else {
        // Regular expression for basic email validation
        var regex = /^S+@S+.S+$/;
        if(regex.test(email) === false) {
            printError("emailErr", "Please enter a valid email address");
        } else{
            printError("emailErr", "");
            emailErr = false;
        }
    }
    
    // Validate mobile number
    if(mobile == "") {
        printError("mobileErr", "Please enter your mobile number");
    } else {
        var regex = /^[1-9]d{9}$/;
        if(regex.test(mobile) === false) {
            printError("mobileErr", "Please enter a valid 10 digit mobile number");
        } else{
            printError("mobileErr", "");
            mobileErr = false;
        }
    }
    
    // Validate country
    if(country == "Select") {
        printError("countryErr", "Please select your country");
    } else {
        printError("countryErr", "");
        countryErr = false;
    }
    
    // Validate gender
    if(gender == "") {
        printError("genderErr", "Please select your gender");
    } else {
        printError("genderErr", "");
        genderErr = false;
    }
    
    // Prevent the form from being submitted if there are any errors
    if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {
       return false;
    } else {
        // Creating a string from input data for preview
        var dataPreview = "You've entered the following details: n" +
                          "Full Name: " + name + "n" +
                          "Email Address: " + email + "n" +
                          "Mobile Number: " + mobile + "n" +
                          "Country: " + country + "n" +
                          "Gender: " + gender + "n";
        if(hobbies.length) {
            dataPreview += "Hobbies: " + hobbies.join(", ");
        }
        // Display input data in a dialog box before submitting the form
        alert(dataPreview);
    }
};

Here in JavaScript, the value of an individual form field can be accessed and retrieved by using the syntax ‘document.formName.fieldName.value’ or ‘document.getElementsByName(name).value’. however, to get the values from a form field that supports multiple selections, like a group of checkboxes, you need to utilize the loop statement as shown in the example above (in lines no-14 to 21).

More so, to check if the format of input data is correct or if we’ve not used the regular expressions.  The technique is an effective one in validating the user’s inputs.

Also, the script above will display the data entered by the user in an alert dialog box for preview purposes before submitting the form to the web server.

Tip: But, we can validate email format using regular expression. However, a user might enter an email that is correctly formatted but does not exist. Hence, the need for authentic email validation; send a confirmation email to the user and verify whether the email exists or not.

 

Adding Style Sheet to Beautify the Form

Last but not the least, create the file named ‘style.css’ and place the code in it, thereafter save it also at the same location where you've saved the previous two files. So, these are the style rules you can use to beautify your form.

body {
    font-size: 16px;
    background: #f9f9f9;
    font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
}
h2 {
    text-align: center;
    text-decoration: underline;
}
form {
    width: 300px;
    background: #fff;
    padding: 15px 40px 40px;
    border: 1px solid #ccc;
    margin: 50px auto 0;
    border-radius: 5px;
}
label {
    display: block;
    margin-bottom: 5px
}
label i {
    color: #999;
    font-size: 80%;
}
input, select {
    border: 1px solid #ccc;
    padding: 10px;
    display: block;
    width: 100%;
    box-sizing: border-box;
    border-radius: 2px;
}
.row {
    padding-bottom: 10px;
}
.form-inline {
    border: 1px solid #ccc;
    padding: 8px 10px 4px;
    border-radius: 2px;
}
.form-inline label, .form-inline input {
    display: inline-block;
    width: auto;
    padding-right: 15px;
}
.error {
    color: red;
    font-size: 90%;
}
input[type="submit"] {
    font-size: 110%;
    font-weight: 100;
    background: #006dcc;
    border-color: #016BC1;
    box-shadow: 0 3px 0 #0165b6;
    color: #fff;
    margin-top: 10px;
    cursor: pointer;
}
input[type="submit"]:hover {
    background: #0165b6;
}

After that, you are almost done, now open the ‘application-form.html’ file in a web browser and try to fill in some data, and see how the script responds when invalid data is entered in a form field.

For a better understanding of server-side validation, please check out the tutorial on PHP form validation

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.