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.

  1. /** Validate Email field */
  2. var email = input.value
  3. var emailRegx = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
  4. if(emailRegx.test(email)){
  5.    ValidInput(input)
  6. }else{
  7.    InvalidInput(input, `Please enter a valid email.`)
  8. }

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.

  1. /** Validate URL field */
  2. var inputURL = input.value
  3. var emailRegx = /^(https|http)?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
  4. if(emailRegx.test(inputURL)){
  5.     ValidInput(input)
  6. }else{
  7.     InvalidInput(input, `Please enter a valid URL. URL must start with https or http.`)
  8. }

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.

  1. /** Validate Password field */
  2.  
  3. var inputPass = input.value
  4. // Check if Password contains lower case character
  5. var hasAlphaLower = inputPass.match(/[a-z]/);
  6. // Check if Password contains upper case character
  7. var hasAlphaUpper = inputPass.match(/[A-Z]/);
  8. // Check if Password contains number character
  9. var hasNumber = inputPass.match(/[0-9]/);
  10. // Check if Password contains valid symbol character
  11. var hasSymbol = inputPass.match(/[\!\@\#\%\&\-\_]/);
  12. // Check if Password Length is >= 8
  13. var validLen = inputPass.length >= 8 ? true : false;
  14. // Check if Password contains invalid Characters
  15. var containsInvalid = (inputPass.replace(/[a-zA-Z0-9\!\@\#\%\&\-\_]/gi,"")).length;
  16. if(hasAlphaLower != null && hasAlphaUpper != null && hasNumber != null && hasSymbol != null && validLen && containsInvalid === 0){
  17.     ValidInput(input)
  18. }else{
  19.     InvalidInput(input, `Please enter a valid Password. Password must contain alphanumeric character and at least 1 valid special character.`)
  20. }

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.

  1.     document.getElementById('sample-form').addEventListener('submit', function(e){
  2.         e.preventDefault()
  3.         //Trigger or write the validation process code here
  4.     })
  5.     document.getElementById('sample-form').querySelectorAll('input').forEach(input => {
  6.         /** Validate input fields value */
  7.         input.addEventListener('input', function(e){
  8.             //Trigger or write the validation process code of the input here
  9.         })
  10.     })

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

  1. /** Font Famaily **/
  2. h1, h2, h3, h4, h5, h6{
  3.     font-family: 'Amatic SC', cursive;
  4. }
  5. html, body{
  6.     height: 100%;
  7.     width: 100%;
  8.     overflow-x: hidden;
  9. }
  10. main{
  11.     width: 100%;
  12.     height: 100%;
  13.     overflow: hidden;
  14.     display: flex;
  15.     flex-direction: column;
  16. }
  17. main>nav,
  18. main>footer
  19. {
  20.     width: 100%;
  21.     flex-shrink: 1;
  22. }
  23. main>div#main-wrapper
  24. {
  25.     width: 100%;
  26.     flex-grow: 1;
  27.     height: calc(100%);
  28.     overflow: auto;
  29. }
  30.  
  31. /** Form Validation Design **/
  32. .error-msg:not(empty) {
  33.     margin-top: 5px;
  34.     font-size: small;
  35.     color: #cf0000;
  36. }
  37. .input-invalid {
  38.     border: 1px solid #f79797;
  39. }
  40. .input-invalid:focus {
  41.     border: 1px solid #fcacac;
  42.     box-shadow: 0 0 0 .25rem #fcacac;
  43. }
  44. .input-success:focus {
  45.     border: 1px solid #6fed95;
  46.     box-shadow: 0 0 0 .25rem #6fed95;
  47. }
  48. .input-success {
  49.     border: 1px solid #7dee9f;
  50. }

Interface

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>JS- Form Validation</title>
  7.     <link rel="preconnect" href="https://fonts.googleapis.com">
  8.     <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  9.     <link href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@700&display=swap" rel="stylesheet">
  10.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  11.     <link rel="stylesheet" href="assets/css/styles.css">
  12.     <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
  13.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  14. </head>
  15.     <main>
  16.         <nav class="navbar navbar-expand-lg navbar-dark bg-gradient bg-dark">
  17.             <div class="container">
  18.                 <a class="navbar-brand" href="./">JS- Form Validation</a>
  19.                 <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  20.             </div>
  21.         </nav>
  22.         <div id="main-wrapper" class="py-5 px-3">
  23.             <div class="container-fluid-md">
  24.                 <h1 class="text-center"><b>Form Validation using Pure JavaScript</b></h1>
  25.                 <hr class="border-3 border-dark mx-auto opacity-100" style="width:80px">
  26.                 <div class="col-lg-6 col-md-8 col-sm-12 col-xs-12 mx-auto">
  27.                     <div class="card rounded-0 shadow">
  28.                         <div class="card-header rounded-0">
  29.                             <div class="card-title"><b>Sample Form</b></div>
  30.                         </div>
  31.                         <div class="card-body rounded-0">
  32.                             <div class="container-fluid">
  33.                                 <form action="" id="sample-form" novalidate>
  34.                                     <div class="mb-3">
  35.                                         <label for="name" class="form-label">Name</label>
  36.                                         <input type="text" class="form-control rounded-0" name="name" id="name" required="required">
  37.                                         <div class="error-msg"></div>
  38.                                     </div>
  39.                                     <div class="mb-3">
  40.                                         <label for="email" class="form-label">Email</label>
  41.                                         <input type="email" class="form-control rounded-0" name="email" id="email" required="required">
  42.                                         <div class="error-msg"></div>
  43.                                     </div>
  44.                                     <div class="mb-3">
  45.                                         <label for="website" class="form-label">Website</label>
  46.                                         <input type="url" class="form-control rounded-0" name="website" id="website" required="required">
  47.                                         <div class="error-msg"></div>
  48.                                     </div>
  49.                                     <div class="mb-3">
  50.                                         <label for="password" class="form-label">Password</label>
  51.                                         <input type="password" class="form-control rounded-0" name="password" id="password" required="required">
  52.                                         <div class="error-msg"></div>
  53.                                         <div class="text-muted mt-1"><small><i>Valid Symbols: @#!-_&%</i></small></div>
  54.                                    </div>
  55.                                </form>
  56.                            </div>
  57.                        </div>
  58.                        <div class="card-footer rounded-0">
  59.                            <div class="col-lg-4 col-md-6 col-sm-10 col-xs-12 mx-auto">
  60.                                <button class="btn btn-primary rounded-pill w-100" form="sample-form">Submit Form</button>
  61.                            </div>
  62.                        </div>
  63.                    </div>
  64.                </div>
  65.            </div>
  66.        </div>
  67.        <footer class="shadow-top py-4 col-auto bg-dark text-light">
  68.            <div class="">
  69.                <div class="text-center">
  70.                    All Rights Reserved &copy; <span id="dt-year"></span> | <span class="text-light fw-bolder">JS- Form Validation</span>
  71.                 </div>
  72.                 <div class="text-center">
  73.                     <a href="mailto:[email protected]" class="text-decoration-none text-light">[email protected]</a>
  74.                 </div>
  75.             </div>
  76.         </footer>
  77.     </main>
  78.     <script src="./assets/js/form-validation.js"></script>
  79. </body>
  80. </html>

Form Validation Script (JS)

form-validation.html

  1. const form = document.getElementById('sample-form')
  2. const inputInvalid = `invalid-input`
  3. const inputValid = `invalid-success`
  4. const inputs = form.querySelectorAll('input')
  5.  
  6. /** Form Submit */
  7. form.addEventListener('submit', function(e){
  8.     e.preventDefault();
  9.  
  10.     /** Validate input fields value */
  11.     inputs.forEach(input => {
  12.         validateFormInput(input)
  13.     })
  14.    
  15.     /** Check for Invalid Input Values */
  16.     if(form.querySelectorAll('input.input-invalid').length <= 0){
  17.         alert("Form is input fields are valid.")
  18.     }
  19. })
  20.  
  21. /** Add Listener to input when user input a character */
  22. inputs.forEach(input => {
  23.     /** Validate input fields value */
  24.     input.addEventListener('input', function(e){
  25.         validateFormInput(input)
  26.     })
  27. })
  28.  
  29.  
  30. /** Input Validation Checker */
  31. window.validateFormInput = function(input){
  32.     var label = input.parentNode.querySelector('label').innerText || "Input";
  33.     var type = input.getAttribute('type') || "text";
  34.  
  35.     if(input.value === "" || input.value == null){
  36.         /** Return Input as Invalid if empty */
  37.         InvalidInput(input, `${label} field is required.`)
  38.     }else if((type).toLowerCase() == "email"){
  39.         /** Validate Email field */
  40.         var inputEmail = input.value
  41.         var emailRegx = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
  42.        if(emailRegx.test(inputEmail)){
  43.            ValidInput(input)
  44.        }else{
  45.            InvalidInput(input, `Please enter a valid email.`)
  46.        }
  47.    }else if((type).toLowerCase() == "url"){
  48.        /** Validate URL field */
  49.        var inputURL = input.value
  50.        var emailRegx = /^(https|http)?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
  51.        if(emailRegx.test(inputURL)){
  52.            ValidInput(input)
  53.        }else{
  54.            InvalidInput(input, `Please enter a valid URL. URL must start with https or http.`)
  55.        }
  56.    }else if((type).toLowerCase() == "password"){
  57.        /** Validate Password field */
  58.  
  59.        var inputPass = input.value
  60.        // Check if Password contains lower case character
  61.        var hasAlphaLower = inputPass.match(/[a-z]/);
  62.        // Check if Password contains upper case character
  63.        var hasAlphaUpper = inputPass.match(/[A-Z]/);
  64.        // Check if Password contains number character
  65.        var hasNumber = inputPass.match(/[0-9]/);
  66.        // Check if Password contains valid symbol character
  67.        var hasSymbol = inputPass.match(/[\!\@\#\%\&\-\_]/);
  68.        // Check if Password Length is >= 8
  69.        var validLen = inputPass.length >= 8 ? true : false;
  70.        // Check if Password contains invalid Characters
  71.        var containsInvalid = (inputPass.replace(/[a-zA-Z0-9\!\@\#\%\&\-\_]/gi,"")).length;
  72.        if(hasAlphaLower != null && hasAlphaUpper != null && hasNumber != null && hasSymbol != null && validLen && containsInvalid === 0){
  73.            ValidInput(input)
  74.        }else{
  75.            InvalidInput(input, `Please enter a valid Password. Password must contain alphanumeric character and at least 1 valid special character.`)
  76.        }
  77.    }else{
  78.        /** Return Success if input is validated */
  79.        ValidInput(input)
  80.    }
  81. }
  82.  
  83. window.ValidInput = function(input){
  84.    /** Update input as valid */
  85.    input.parentNode.querySelector('.error-msg').innerText = ``
  86.    if(input.classList.contains('input-invalid'))
  87.        input.classList.remove('input-invalid')
  88.    if(!input.classList.contains('input-success'))
  89.        input.classList.add('input-success')
  90.    return;
  91. }
  92. window.InvalidInput = function(input, msg){
  93.    /** Update input as invalid */
  94.    input.parentNode.querySelector('.error-msg').innerText = `${msg}`
  95.    if(input.classList.contains('input-success'))
  96.        input.classList.remove('input-success')
  97.    if(!input.classList.contains('input-invalid'))
  98.        input.classList.add('input-invalid')
  99.    return;
  100. }

Snapshots

Form Page Interface

JS- form validation

Valid Input Field

JS- form validation

Invalid Input Field

JS- form validation

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