Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
           CodeHim.com

Free Web Design Code & Scripts

       
  • Home
  • Code Snippets
    • Accordion
    • Creative
    • Carousel
    • Date & Time
    • Gallery
    • LightBox
    • Menu & Nav
    • Modal
    • Others
    • Portfolio
    • Social Media
    • Text & Input
    • Video Player
    • Zoom
  • HTML & CSS
  • Bootstrap
  • JavaScript
  • Collections
  • About
  • Contact
  • Buy Me a Coffee

Home / Text & Input / Form Validation in JavaScript Code

Form Validation in JavaScript Code

January 22, 2024January 11, 2024 by Asif Mughal
Form Validation in JavaScript Code
Share This:
Code Snippet:JS Form Validation
Author: Abdullah Sajjad
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 11,548
License: MIT
Edit Code online: View on CodePen
Read More
 Demo
Download (File path is not allowed!)

This JavaScript code snippet helps you to create a form validation feature on the form submit. It validates username, email, and password and displays the inline error message in case of invalid input. You can integrate this vanilla JavaScript code for registration/signup forms to validate inputs on submit.

This form validation snippet doesn’t require any additional library or plugin. It uses JavaScript regular expressions to validate emails. It allows setting min/max length rules for input validation.  Moreover, it can be integrated with your existing HTML forms.

How to Create Form Validation in JavaScript

1. First you need to create the HTML form element with username, email, and password input with validation attributes.

 <div class="container">
    <form id="form" class="form">
        <h2>Register With Us</h2>
        <div class="form-control">
            <label for="username">Username</label>
            <input type="text" id="username" placeholder="Enter Username">
            <small>Error Message</small>
        </div>
        <div class="form-control">
            <label for="email">Email</label>
            <input type="text" id="email" placeholder="Enter email">
            <small>Error Message</small>
        </div>
        <div class="form-control">
            <label for="password">Password</label>
            <input type="password" id="password" placeholder="Enter password">
            <small>Error Message</small>
        </div>
        <div class="form-control">
            <label for="password2">Confirm Password</label>
            <input type="password" id="password2" placeholder="Enter password again">
            <small>Error Message</small>
        </div>
        <button>Submit</button>
    </form>
</div>

2. After that, define the CSS styles for HTML form inputs, success, and error messages as follows.

:root{
    --succes-color: #2ecc71;;
    --error-color: #e74c3c;
}
.container{
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.3);
    width: 400px;
    margin: 10px auto;
}
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;
    display: block;
    width: 100%;
    padding: 10px;
    font-size: 14px;   
}
.form-control input:focus{
    outline: 0;
    border-color: #777;

}
.form-control.success input {
    border-color: var(--succes-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 solid #3498db;
    border-radius: 4px;
    color: #fff;
    display: block;
    padding: 10px;
    font-size: 16px;
    margin-top:20px;
    width:100%;
}

3. Finally, include the form validation JavaScript code in your project and done.

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 messages
function showError(input, message) {
    const formControl = input.parentElement;
    formControl.className = 'form-control error';
    const small = formControl.querySelector('small');
    small.innerText = message;
}

//show success colour
function showSucces(input) {
    const formControl = input.parentElement;
    formControl.className = 'form-control success';
}

//check email is valid
function checkEmail(input) {
    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,}))$/;
    if(re.test(input.value.trim())) {
        showSucces(input)
    }else {
        showError(input,'Email is not invalid');
    }
}

//checkRequired fields
function checkRequired(inputArr) {
    inputArr.forEach(function(input){
        if(input.value.trim() === ''){
            showError(input,`${getFieldName(input)} is required`)
        }else {
            showSucces(input);
        }
    });
}

//check input Length
function checkLength(input, min ,max) {
    if(input.value.length < min) {
        showError(input, `${getFieldName(input)} must be at least ${min} characters`);
    }else if(input.value.length > max) {
        showError(input, `${getFieldName(input)} must be les than ${max} characters`);
    }else {
        showSucces(input);
    }
}

//get FieldName
function getFieldName(input) {
    return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}

// check passwords match
function checkPasswordMatch(input1, input2) {
    if(input1.value !== input2.value) {
        showError(input2, 'Passwords do not match');
    }
}

//Event Listeners
form.addEventListener('submit',function(e) {
    e.preventDefault();

    checkRequired([username, email, password, password2]);
    checkLength(username,3,15);
    checkLength(password,6,25);
    checkEmail(email);
    checkPasswordMatch(password, password2);
}); 

That’s all! hopefully, this JavaScript validation plugin is helpful for you. If you have any questions or suggestions, let me know by comment below.

Similar Code Snippets:

  • JavaScript JSON Array Pagination

    JavaScript JSON Array Pagination

  • jQuery Animate Numbers - Animated Number Increase

    jQuery Animate Numbers - Animated Number Increase

  • Light Dark Theme Toggle with CSS and JavaScript

    Light/Dark Theme Toggle with CSS and JavaScript

  • JavaScript Avatar Generator

    JavaScript Avatar Generator

  • Card Flip Animation using JavaScript Code

    Card Flip Animation using JavaScript Code

  • JavaScript Detect Media Query Change

    JavaScript Detect Media Query Changes

  • To Do List Project in JavaScript

    To Do List Project in JavaScript

  • JavaScript / jQuery Autocomplete Textbox From Array

    JavaScript / jQuery Autocomplete Textbox From Array

  • jQuery Multiple Image Upload with Preview and Delete

    jQuery Multiple Image Upload with Preview and Delete

Asif Mughal

I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.

Categories Text & Input, Vanilla JavaScript Tags Password Validation
Pure CSS Stylish Dropdown Menu
Simple Tabs in HTML CSS and JavaScript

Leave a Comment Cancel reply

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

  • Categories

    • Accordion 22
    • Bootstrap 81
      • Bootstrap Accordion 1
      • Bootstrap Buttons 4
      • Bootstrap Cards 2
      • Bootstrap Carousel 2
      • Bootstrap Dropdowns 2
      • Bootstrap Forms 6
      • Bootstrap Jumbotron 1
      • Bootstrap Modals 2
      • Bootstrap Navbars 6
      • Bootstrap Panels 1
      • Bootstrap Progress Bars 1
      • Bootstrap Text & Input 3
    • Carousel 58
    • Chart & Graph 15
    • Date & Time 49
    • Gallery 39
    • HTML5 & CSS3 201
    • Layout 17
    • LightBox 19
    • Menu & Nav 95
    • Modal 18
    • Others 58
    • Portfolio 8
    • Social Media 10
    • Text & Input 120
    • Vanilla JavaScript 163
    • Zoom 12

You May Like

Alert (7) Analog Clock (4) Analog Clocks (5) Back to Top (4) Calculator (16) Calendar (5) Chart (3) Color Picker (4) Contact Us Forms (5) Countdown Timer (6) Datepicker (9) Digital Clocks (10) Drag and Drop (4) Dropdown Menu (23) File Uploader (4) Hamburger Menu (9) Horizontal Menu (24) Hover Effects (5) HTML5 Canvas (8) Image Sliders (40) Mega Menu (11) Modal (5) Multi-Level Menu (9) News Ticker (4) Notification (9) Off-Canvas Menu (10) Pagination (5) Parallax (8) Popup Lightbox (20) Progress Bar (5) Range Sliders (4) Scrolling Effects (28) Search Box (4) Select Dropdown (4) Shopping Cart (3) Side Menu (16) Slideshow (19) Social Share Buttons (3) Tabs (9) Text (11) Timeline (5) Timer (4) Tooltip (4) Typing Effect (6) Vertical Menu (14)

Latest Code Snippets

  • Common Open Source Security Vulnerabilities and How to Mitigate ThemCommon Open Source Security Vulnerabilities and How to Mitigate Them
    October 12, 2024
  • Animating Grid-column on Hover Using CSSAnimating Grid-column on Hover Using CSS
    April 1, 2024
  • Star Trails Animation On Mousemove in JavaScriptStar Trails Animation On Mousemove in JavaScript
    March 31, 2024
  • Gravity Button Using Pure CSSGravity Button Using Pure CSS
    March 31, 2024
  • Padlock Toggle Switch in CSSPadlock Toggle Switch in CSS
    March 31, 2024
  • Scroll-driven Animations in Pure CSSScroll-driven Animations in Pure CSS
    March 31, 2024
  • Interactive Notification Center UI in Vanilla JSInteractive Notification Center UI in Vanilla JS
    March 31, 2024
  • Emoji Spinner in Vanilla JavaScriptEmoji Spinner in Vanilla JavaScript
    March 31, 2024
  • Reveal Secret Code Using CSSReveal Secret Code Using CSS
    March 31, 2024
  • Toggle Button in CSS With Stretchable Elastic EffectToggle Button in CSS With Stretchable Elastic Effect
    March 31, 2024

Popular

  • 65+ Login Page in HTML with CSS Code Sample Simple to Difficult - 947,410 views
  • 25+ Best JavaScript Shopping Cart Examples with Demo - 211,942 views
  • Bootstrap Multiselect Dropdown with Checkboxes - 150,950 views
  • Bootstrap 5 Buttons with Icon and Text Tutorial & Demo - 112,360 views
  • 19+ Bootstrap Select Dropdown with Search Box Tutorial & Examples - 101,041 views
  • Bootstrap 5 Sidebar Menu with Submenu Collapse/Hover Tutorial Demo - 88,106 views
  • 99+ Social Media Buttons HTML Code Sample & Tutorial - 86,393 views
  • 19+ Bootstrap 5 Mega Menu Responsive/Drop Down Examples - 86,390 views
  • Bootstrap 4 Modal Popup Login Form Tutorial & Demo - 82,150 views
  • Bootstrap Vertical Menu with Submenu on Click - 80,202 views

Advertisement

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...

CodeHim
  • About
  • Contact Us
  • Terms and Conditions
  • Privacy Policy
Top Categories
  • Bootstrap Snippets
  • JavaScript Snippets
  • HTML CSS Snippets
  • Menu & Nav Snippets
Get in Touch

Follow us on social media to be updated with latest web design code & scripts...

All Rights Reserved © 2026 - CodeHim Inc

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

F5
X