Form Validation using JavaScript
In this article, I will be providing a simple web application to demonstrate how Form Validation works using JavaScript. This example is ideal for beginners and developers who want to understand the basics of client-side form validation in web development.
The form will include commonly used input fields such as the email and the password, along with JavaScript functions that validate user input in real time. This ensures that the data entered meets specific criteria before submission, helping to prevent errors and improve data quality.
Implementing JavaScript form validation enhances the user experience by providing instant feedback and reducing unnecessary server requests. It also plays a crucial role in maintaining the integrity and security of web applications. Whether you're building a contact form, registration form, or login system, understanding form validation is a key skill in modern web development.
What is Form Validation?
Form validation is a crucial technique in web development used to verify that user input in a web form such as in login forms, registration forms, contact forms, and other data entry interfaces is accurate, complete, and properly formatted before it is submitted to or processed by the server. It acts as the first line of defense against incorrect or malicious input, ensuring that the data collected is clean and reliable.
Implementing effective form validation using JavaScript or server-side scripting not only maintains data integrity but also significantly enhances the user experience. It provides instant feedback to users, guiding them to correct mistakes before submission, which minimizes errors and reduces server load. Additionally, it helps prevent security vulnerabilities such as SQL injection or malformed data entries.
By improving the accuracy and quality of user input, form validation contributes to the overall functionality, usability, and professionalism of a website or web application. It is an essential practice for developers aiming to build secure, user-friendly, and high-performance digital platforms.
About the Application
The application we are about to create is a simple web-based form that includes the following input fields: Username, Email, Password, and Confirm Password. This form is designed to demonstrate the use of JavaScript form validation to ensure accurate and secure user input before submission.
The validation process is triggered when the user clicks the Submit button. Each input field will be checked for completeness and correctness. If a field is left empty, the validation script will immediately display an error message next to the field, prompting the user to fill in the required information. If the email address entered does not follow a valid email format (e.g., [email protected]), the form will display a corresponding validation error.
Additionally, the Password and Confirm Password fields are compared to ensure that they match. If they do not, an error message will alert the user to correct the mismatch. To provide a visual indicator of the input status, the form uses colored borders: green borders for valid inputs and red borders for invalid ones. This type of user feedback not only improves form usability but also enhances the overall user experience and encourages proper data entry.
Let's start the coding...
Creating the Interface
First, let's create a new HTML file and name it as index.html. This file contains the relevant elements for the application including the form container, fields, and button. See the following script.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="style.css">
- <titleForm validation</title>
- </head>
- <body>
- <div class="container">
- <form id="form" class="form" autocomplete="off">
- <div class="form-control">
- <input type="text" id="username" placeholder="Enter username">
- </div>
- <div class="form-control">
- <input type="text" id="email" placeholder="Enter email">
- </div>
- <div class="form-control">
- <input type="password" id="password" placeholder="Enter password">
- </div>
- <div class="form-control">
- <input type="password" id="password2" placeholder="Enter password again">
- </div>
- </form>
- </div>
- </body>
- </html>
Designing the Interface
Next, let's create new CSS file and name it as style.css. This file will contain the stylesheet script that design some structure and elements of the interface. Checkout the following script.
- @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@600&display=swap');
- :root{
- --success-color:#2ecc71;
- --error-color: #e74c3c;
- }
- *{
- box-sizing: border-box;
- }
- body{
- background-color: #f9fafb;
- font-family:'Open Sans',sans-serif;
- display: flex;
- align-items: center;
- justify-content: center;
- min-height: 100vh;
- margin: 0;
- }
- .container{
- background-color: #fff;
- border-radius: 5px;
- box-shadow: 0 2px 10px rgba(0,0,0, 0.3);
- width: 400px;
- }
- h2{
- text-align: center;
- margin: 0 0 20px;
- }
- .form{
- padding: 30px 40px;
- }
- .form-control{
- margin-bottom: 10px;
- padding-bottom: 20px;
- position: relative;
- }
- .form-control label{
- color: #777;
- display: block;
- margin-bottom: 5px;
- }
- .form-control input{
- border: 2px solid #f0f0f0;
- border-radius: 4px;
- width: 100%;
- padding: 10px;
- font-size: 14px;
- }
- .form-control input:focus{
- outline: 0;
- border-color: #777;
- }
- .form-control.success input{
- border-color:var(--success-color);
- }
- .form-control.error input{
- border-color:var(--error-color);
- }
- .form-control small{
- color: var(--error-color);
- position: absolute;
- bottom: 0;
- left: 0;
- visibility: hidden;
- }
- .form-control.error small{
- visibility: visible;
- }
- .form button{
- cursor: pointer;
- background-color: #3498db;
- border: 2px sold #3498db;
- border-radius: 4px;
- color: #fff;
- display: block;
- font-size: 16px;
- padding: 10px;
- margin-top: 10px;
- width: 100%;
- }
Creating the JavaScript
Lastly, let's create the JavaScript naming App.js. This file contains main script of the application. The script makes the form validation feature of this application functional. Checkout the script below.
- const form=document.getElementById('form');
- const username=document.getElementById('username');
- const email=document.getElementById('email');
- const password=document.getElementById('password');
- const password2=document.getElementById('password2');
- //Show input error message
- function showError(input,message){
- const formControl=input.parentElement;
- formControl.className='form-control error';
- const small=formControl.querySelector('small');
- small.innerText=message;
- }
- function showSuccess(input){
- const formControl=input.parentElement;
- formControl.className='form-control success';
- }
- //Email
- function isValidEmail(email)
- {
- const re= /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
- return re.test(String(email).toLowerCase());
- }
- form.addEventListener('submit',function(e){
- e.preventDefault();
- if(username.value===''){
- showError(username,'Username is required');
- }
- else{
- showSuccess(username);
- }
- if(email.value===''){
- showError(email,'Email is required');
- }else if(!isValidEmail(email.value)){
- showError(email,'Email is not valid');
- }
- else{
- showSuccess(email);
- }
- if(password.value===''){
- showError(password,'Password is required');
- }
- else{
- showSuccess(password);
- }
- if(password2.value===''){
- showError(password2,'confirm password is required');
- }
- else{
- showSuccess(password2);
- }
- if((password.value).toLowerCase() === (password2.value).toLowerCase())
- {
- showSuccess(password2);
- }else{
- showError(password2,'password does not match');
- }
- });
Snapshot
Form with Invalid Data
Form with Valid Data
There you have it! I have also provided the full source code zip file on this website and is free to download. Feel free to download and modify it the way you wanted.
I hope this Form Validation using JavaScript will help you with what you are looking for and you'll find useful from the scripts for your own current or future projects.
Explore more on this website for more Tutorial, Free Source Codes, and Articles covering various programming languages.
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.
Add new comment
- 23 views