Contact Form Validation in JavaScript

Contact Form Validation in JavaScript
Code Snippet: Form Validation
Author: Zaine Kingi
Published: January 17, 2024
Last Updated: January 22, 2024
Downloads: 15,778
License: MIT
Edit Code online: View on CodePen
Read More

The “Form Validation” is a lightweight JavaScript plugin to validate the contact form. It uses the JavaScript RegExp object to validate the username, email, and phone number. The regular expressions match the characters on the form submit event and return an error message in case of an invalid entry. The contact form comes with a simple and clean design with all necessary inputs. So, it’s ready to integrate into your project.

How to Create Contact Form Validation in JavaScript

1. First of all, create the HTML form element with name, email, phone, and message input. Create a span element with the class name “errors” and place it after each input. Similarly, create a submit button, wrap the form element into a div element and define a class name “form-container”.

 <div class="form-container">
  <h1>Contact Form</h1>
  <form name="contactForm" method="post" onsubmit = "return validate()" action="#">
    <label for="name">* Name</label>
    <input type="text" id="name" name="name" placeholder="Your name" >
    <span class="errors"></span><br>

    <label for="email">* Email</label>
    <input type="text" placeholder="Email address" id="email" name="email" >
    <span class="errors"></span><br>

    <label for="phone">* Phone</label>
    <input type="text" placeholder="Phone number" id="phone" name="phone" >
    <span class="errors"></span><br>
    
    <label for="subject">* Message</label>
    <textarea placeholder="Your message" cols="132" rows="5" name="subject" id="subject"></textarea>
    <span class="errors"></span><br>

    <button type="submit" value="Submit">Submit</button>
  </form>
</div>

2. After that, add the following CSS styles to your project to design the contact form. You can set the custom values for CSS to customize the contact form.

body {
  font-family: sans-serif;
}
.form-container {
  width: 50%;
  margin: auto;
  padding: 2%;
  border: 1px solid #f7f7f7;
}
label {
  display: block;
  margin-top: 25px;
  font-size: 1rem;
}
input, textarea {
  width: 80%;
  padding: 15px;
  font-size: 1rem;
  border: 1px solid #ccc;
}
button {
  width: 82.5%;
  height: 50px;
  border-radius: 5px;
  color: #fff;
  background: red;
  line-height: 1rem;
  font-size: 1rem;
  cursor: pointer;
  border: 1px solid red;
  margin-top: 25px;
  transition: color .4s ease-out, background .4s ease-out;
}
button:hover {
  color: red;
  background: #fff;
}
.errors {
  display: block;
  color: red;
  margin-top: 5px;
}
.error {
  -webkit-transition: .2s;
  -moz-transition: .2s;
  -ms-transition: .2s;
  -o-transition: .2s;
  transition: .2s;
  box-shadow: 0 0 15px 0 rgba(255,36,0,1);
}

3. Finally, add the following JavaScript validate function between the <script> and </script> tag before closing the body element. Trigger this function on the form submit event as described in the HTML code.

var validate = function(e) {
    var fields = document.querySelectorAll('.form-container textarea, .form-container input[type="text"]');
    var regEx;
    var removeSpan;
    var par;
    var check = false;
    var val;
    var errArr = [];

    for (var i = 0; i < fields.length; i++) {
        if (fields[i].value === "") {
          
            if (fields[i].nextElementSibling.classList.contains('error')) {
              removeSpan = fields[i].nextElementSibling;
              par = fields[i].parentNode;
              par.removeChild(removeSpan);
              fields[i].nextElementSibling.innerHTML = "Hmmm! " + fields[i].placeholder + " is required?";
              fields[i].style.boxShadow = "0 0 2px 1px #cc0001";
              check = false;
              errArr.push(fields[i]);
            }
            fields[i].nextElementSibling.innerHTML = "Hmmm! " + fields[i].placeholder + " is required?";
            fields[i].style.boxShadow = "0 0 2px 1px #cc0001";
            check = false;
            errArr.push(fields[i]);
        } else {

            // check if message and name values contain valid characters.
            if (fields[i].id !== 'email' && fields[i].id !== 'phone') {
                val = isValidChar(fields[i]);
                if(val === false) {
                  fields[i].nextElementSibling.innerHTML = "Are you trying to HACK ME!";
                  fields[i].style.boxShadow = "0 0 2px 1px #cc0001";
                  check = false;
                  errArr.push(fields[i]);
                } else {
                  fields[i].nextElementSibling.innerHTML = "";
                  fields[i].style.boxShadow = "none";
                  check = true;
                }
            }
          
            if(fields[i].id === 'phone') {
              val = isValidPhone(fields[i]);
              if(val === false) {
                fields[i].nextElementSibling.innerHTML = "Hmmm! Your phone number is not valid?";
                fields[i].style.boxShadow = "0 0 2px 1px #cc0001";
                check = false;
                errArr.push(fields[i]);
              } else {
                fields[i].nextElementSibling.innerHTML = "";
                fields[i].style.boxShadow = "none";
                check = true;  
              }
            }

            if (fields[i].id === 'email') {
                val = isValidEmail(fields[i]);
                if(val === false) {
                    fields[i].nextElementSibling.innerHTML = "Hmmm! Your email address is not valid?";
                    fields[i].style.boxShadow = "0 0 2px 1px #cc0001";
                    check = false;
                    errArr.push(fields[i]);
                } else {
                    fields[i].nextElementSibling.innerHTML = "";
                    fields[i].style.boxShadow = "none";
                    check = true;
                }
            }
        }
    }
  
    if(check === false) {
      var count = 0;
      var toErr = setInterval(function() {
        var e = errArr[0].offsetTop + -25;
        var pos = Math.abs(e);
        if(count < pos) {
          count ++;
          window.scrollTo(0, count);
        } else {
          clearInterval(toErr);
        }
      }, 1);
    }
    
    return check

    // Helper functions.
    function isValidEmail(e) {
        regEx = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        var email = e.value;
        if (!regEx.test(email)) {
            return false;
        }
    }

    function isValidChar(e) {
        regEx = /^[a-zA-Z@#$%!?^&*()_+\-=\[\]{};':"\\|,.\/? ]*$/;
        var value = e.value;
        if (!regEx.test(value)) {
            return false;
        }
    }
  
    function isValidPhone(e) {
      regEx = /^[+]?[(]?[+]?\d{2,4}[)]?[-\s]?\d{2,8}[-\s]?\d{2,8}$/;
      var value = e.value;
      if(!regEx.test(value)) {
        return false;
      }
    }
};

That’s all! hopefully, you have successfully integrated this contact form validation code snippet into your project. If you have any questions or facing any issues, feel free to comment below.

4 thoughts on “Contact Form Validation in JavaScript”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X