Creating a Form Validation Before and Upon Submission using JavaScript Tutorial
In this tutorial, you will learn how to create a Form Validation before and upon the submission of the form in JavaScript without using any other JS library. The tutorial aims to provide the students, self-learners, and new programmers with a reference as their guide for enhancing their JS programming capabilities for building their current and future web applications. Here, snippets and source code scripts are provided to give you a better understanding of achieving our goal in this tutorial. A sample source code zip file is also provided and is free to download.
JS Form Validator Libraries are available on the internet and are free to download and use. In this tutorial, you will understand and have an Idea of how the form validators are created.
What is Form Validation?
Form Validation is a technical process of web forms to check the validity of the input values. With this, end-users will be either notified if they entered an invalid value to the field or can't proceed with the submission of the form. The form validation may also prevent some human errors.
How to create Form Validation using JavaScript?
Javascript comes with multiple built-in functions and methods that are useful for creating Form Validation such as Event Listeners, Query/Element Selectors, and more.
Here are some of the following JS functions/methods that can help us to achieve the Form Validation feature before and upon submission of the form:
- click Event Listener
- input Event Listener
- submit Event Listener
- match method
- test method
- classList property (add, remove, and contains)
- and element selectors
Input Validations
Here are some snippets for validating some types of input values.
Email Validation
We can validate if the given value of the user in the email input is a valid email using the test method of JS. Using the regular expression we can test the email if it is valid.
- /** Validate Email field */
- var email = input.value
- var emailRegx = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
- if(emailRegx.test(email)){
- ValidInput(input)
- }else{
- InvalidInput(input, `Please enter a valid email.`)
- }
URL Validation
We can do the same technique of validating the email to validate the URL. The only difference between the two is the pattern used for validating.
- /** Validate URL field */
- var inputURL = input.value
- var emailRegx = /^(https|http)?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
- if(emailRegx.test(inputURL)){
- ValidInput(input)
- }else{
- InvalidInput(input, `Please enter a valid URL. URL must start with https or http.`)
- }
Password Validation
For Validating Passwords, we can use the match method of JS so we can identify if the entered password value contains the valid characters for the password. Also, replace method is also useful for this to temporarily remove the valid characters from the value and check if there's an invalid character. See the following snippet.
- /** Validate Password field */
- var inputPass = input.value
- // Check if Password contains lower case character
- var hasAlphaLower = inputPass.match(/[a-z]/);
- // Check if Password contains upper case character
- var hasAlphaUpper = inputPass.match(/[A-Z]/);
- // Check if Password contains number character
- var hasNumber = inputPass.match(/[0-9]/);
- // Check if Password contains valid symbol character
- var hasSymbol = inputPass.match(/[\!\@\#\%\&\-\_]/);
- // Check if Password Length is >= 8
- var validLen = inputPass.length >= 8 ? true : false;
- // Check if Password contains invalid Characters
- var containsInvalid = (inputPass.replace(/[a-zA-Z0-9\!\@\#\%\&\-\_]/gi,"")).length;
- if(hasAlphaLower != null && hasAlphaUpper != null && hasNumber != null && hasSymbol != null && validLen && containsInvalid === 0){
- ValidInput(input)
- }else{
- InvalidInput(input, `Please enter a valid Password. Password must contain alphanumeric character and at least 1 valid special character.`)
- }
Form Validations Before and Upon Form Submission
To trigger the form validation process before and upon submission of the form, we can use the input and submit event listeners. The input event listener is for the input fields so we can trigger the validation process while the user updates the input value. The submit event listener is for the form so we can trigger the validation for all input once more before the submission.
- document.getElementById('sample-form').addEventListener('submit', function(e){
- e.preventDefault()
- //Trigger or write the validation process code here
- })
- document.getElementById('sample-form').querySelectorAll('input').forEach(input => {
- /** Validate input fields value */
- input.addEventListener('input', function(e){
- //Trigger or write the validation process code of the input here
- })
- })
Example Source Code
Here are the scripts of a simple web application that demonstrate the Form Validation Process before and upon the submission of the form.
Custom CSS
styles.css
- /** Font Famaily **/
- h1, h2, h3, h4, h5, h6{
- font-family: 'Amatic SC', cursive;
- }
- html, body{
- height: 100%;
- width: 100%;
- overflow-x: hidden;
- }
- main{
- width: 100%;
- height: 100%;
- overflow: hidden;
- display: flex;
- flex-direction: column;
- }
- main>nav,
- main>footer
- {
- width: 100%;
- flex-shrink: 1;
- }
- main>div#main-wrapper
- {
- width: 100%;
- flex-grow: 1;
- height: calc(100%);
- overflow: auto;
- }
- /** Form Validation Design **/
- .error-msg:not(empty) {
- margin-top: 5px;
- font-size: small;
- color: #cf0000;
- }
- .input-invalid {
- border: 1px solid #f79797;
- }
- .input-invalid:focus {
- border: 1px solid #fcacac;
- box-shadow: 0 0 0 .25rem #fcacac;
- }
- .input-success:focus {
- border: 1px solid #6fed95;
- box-shadow: 0 0 0 .25rem #6fed95;
- }
- .input-success {
- border: 1px solid #7dee9f;
- }
Interface
index.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="preconnect" href="https://fonts.googleapis.com">
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
- <link href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@700&display=swap" rel="stylesheet">
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
- <link rel="stylesheet" href="assets/css/styles.css">
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
- </head>
- <body>
- <main>
- <nav class="navbar navbar-expand-lg navbar-dark bg-gradient bg-dark">
- <div class="container">
- </div>
- </nav>
- <div id="main-wrapper" class="py-5 px-3">
- <div class="container-fluid-md">
- <hr class="border-3 border-dark mx-auto opacity-100" style="width:80px">
- <div class="col-lg-6 col-md-8 col-sm-12 col-xs-12 mx-auto">
- <div class="card rounded-0 shadow">
- <div class="card-header rounded-0">
- </div>
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <form action="" id="sample-form" novalidate>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" name="name" id="name" required="required">
- </div>
- <div class="mb-3">
- <input type="email" class="form-control rounded-0" name="email" id="email" required="required">
- </div>
- <div class="mb-3">
- <input type="url" class="form-control rounded-0" name="website" id="website" required="required">
- </div>
- <div class="mb-3">
- <input type="password" class="form-control rounded-0" name="password" id="password" required="required">
- </div>
- </form>
- </div>
- </div>
- <div class="card-footer rounded-0">
- <div class="col-lg-4 col-md-6 col-sm-10 col-xs-12 mx-auto">
- <button class="btn btn-primary rounded-pill w-100" form="sample-form">Submit Form</button>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <footer class="shadow-top py-4 col-auto bg-dark text-light">
- <div class="">
- <div class="text-center">
- </div>
- <div class="text-center">
- </div>
- </div>
- </footer>
- </main>
- </body>
- </html>
Form Validation Script (JS)
form-validation.html
- const form = document.getElementById('sample-form')
- const inputInvalid = `invalid-input`
- const inputValid = `invalid-success`
- const inputs = form.querySelectorAll('input')
- /** Form Submit */
- form.addEventListener('submit', function(e){
- e.preventDefault();
- /** Validate input fields value */
- inputs.forEach(input => {
- validateFormInput(input)
- })
- /** Check for Invalid Input Values */
- if(form.querySelectorAll('input.input-invalid').length <= 0){
- alert("Form is input fields are valid.")
- }
- })
- /** Add Listener to input when user input a character */
- inputs.forEach(input => {
- /** Validate input fields value */
- input.addEventListener('input', function(e){
- validateFormInput(input)
- })
- })
- /** Input Validation Checker */
- window.validateFormInput = function(input){
- var label = input.parentNode.querySelector('label').innerText || "Input";
- var type = input.getAttribute('type') || "text";
- if(input.value === "" || input.value == null){
- /** Return Input as Invalid if empty */
- InvalidInput(input, `${label} field is required.`)
- }else if((type).toLowerCase() == "email"){
- /** Validate Email field */
- var inputEmail = input.value
- var emailRegx = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
- if(emailRegx.test(inputEmail)){
- ValidInput(input)
- }else{
- InvalidInput(input, `Please enter a valid email.`)
- }
- }else if((type).toLowerCase() == "url"){
- /** Validate URL field */
- var inputURL = input.value
- var emailRegx = /^(https|http)?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
- if(emailRegx.test(inputURL)){
- ValidInput(input)
- }else{
- InvalidInput(input, `Please enter a valid URL. URL must start with https or http.`)
- }
- }else if((type).toLowerCase() == "password"){
- /** Validate Password field */
- var inputPass = input.value
- // Check if Password contains lower case character
- var hasAlphaLower = inputPass.match(/[a-z]/);
- // Check if Password contains upper case character
- var hasAlphaUpper = inputPass.match(/[A-Z]/);
- // Check if Password contains number character
- var hasNumber = inputPass.match(/[0-9]/);
- // Check if Password contains valid symbol character
- var hasSymbol = inputPass.match(/[\!\@\#\%\&\-\_]/);
- // Check if Password Length is >= 8
- var validLen = inputPass.length >= 8 ? true : false;
- // Check if Password contains invalid Characters
- var containsInvalid = (inputPass.replace(/[a-zA-Z0-9\!\@\#\%\&\-\_]/gi,"")).length;
- if(hasAlphaLower != null && hasAlphaUpper != null && hasNumber != null && hasSymbol != null && validLen && containsInvalid === 0){
- ValidInput(input)
- }else{
- InvalidInput(input, `Please enter a valid Password. Password must contain alphanumeric character and at least 1 valid special character.`)
- }
- }else{
- /** Return Success if input is validated */
- ValidInput(input)
- }
- }
- window.ValidInput = function(input){
- /** Update input as valid */
- input.parentNode.querySelector('.error-msg').innerText = ``
- if(input.classList.contains('input-invalid'))
- input.classList.remove('input-invalid')
- if(!input.classList.contains('input-success'))
- input.classList.add('input-success')
- return;
- }
- window.InvalidInput = function(input, msg){
- /** Update input as invalid */
- input.parentNode.querySelector('.error-msg').innerText = `${msg}`
- if(input.classList.contains('input-success'))
- input.classList.remove('input-success')
- if(!input.classList.contains('input-invalid'))
- input.classList.add('input-invalid')
- return;
- }
Snapshots
Form Page Interface
Valid Input Field
Invalid Input Field
There you go! I have provided also the complete source code zip file that I created for this tutorial on this site and it is free to download. The download button is located below this tutorial's content.
That's it! I hope this Creating a Form Validation Before and Upon Submission using JavaScript Tutorial will help you with what you are looking for and will be useful for current and future web application projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding =)
Add new comment
- 276 views