Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Javascript Project to Validate HTML5 Form With Error Messages Using CSS3

Posted on October 12, 2022

 

 

Welcome folks today in this blog post we will be doing form validation in javascript using html5 & css3. All the full source code of the application is given below.

 

 

Get Started

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<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>

 

 

As you can see we have the different input fields for username, email , password and confirm password fields. And also we have the labels for all the different input fields. And we will showing the error messages inside the small tag. And also we have the submit button to submit the form.

 

 

As you can see we have the different fields out there and also we have the placeholders for error messages. And also we have the submit button.

 

 

And now we need to style this form using some css classes. Basically it will style the input fields and also style the error messages styling as well which including the positioning and color of the messages as well.

 

 

CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');
 
:root{
    --succes-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;
    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%;
}

 

 

 

 

 

And now as you can see we have successfully styled the input fields and button. Now we need to write the javascript code to do the form validation for these input fields.

 

 

JavaScript
1
2
3
4
5
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');

 

 

As you can see we are getting the references of all the DOM Elements inside the HTML5. We have got all the references of all the input fields using the id.

 

JavaScript
1
2
3
4
5
6
7
8
9
10
//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);
});

 

 

As you can see we are attaching the event Listener to the form element. When the form element is submitted we are preventing the auto submission of the form. And then we are calling the different form validation methods. First of all we are calling the checkReqired() method which will check whether the username,email,password and confirm password are empty or not. Now we need to define this function in the next step

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
//checkRequired fields
function checkRequired(inputArr) {
    inputArr.forEach(function(input){
        if(input.value.trim() === ''){
            showError(input,`${getFieldName(input)} is required`)
        }else {
            showSucces(input);
        }
    });
}

 

 

So now inside this function we are first of all using the forEach() method to loop through the given array. For each input we are checking whether the given input value is empty or not. We are using the trim() method If it’s empty then we are calling the showError() method passing the input field and then we are passing the message as well. If the fields are correct then we are calling the showSuccess() method

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
//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';
}

 

 

So as you can see we are defining the showError() and showSuccess() methods. Inside these methods we are attaching the dynamic css classes that we defined inside the css file to the form input field. We are attaching the error message to the small element. We are manipulating small.innerText() method to attach the message.

 

 

 

 

Now we will be defining the second validation method which is checking the length of the input field. The length should be between 3 & 15 characters. The function are shown as below

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
//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);
    }
}

 

 

As you can see we are receiving the input element and then we have also have min and max length received as an argument in the function. And then we have the if condition to check the value of the input field. If it’s less and more than the limit then we are showing the error message else we are showing the success message.

 

 

 

 

So as you can see we are having the validation error if we cross the limit which is set. This is the validation error message showing in the browser.

 

So Now we will be doing the validation of the email whether the email is valid or not using the regular expression. So now we will write the function to check whether the email is valid or not

 

 

JavaScript
1
2
3
4
5
6
7
8
9
//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');
    }
}

 

 

Here in the above function we are having a regular expression which checks for whether the email is valid or not. And then we are calling the showError() method

 

 

 

 

And now we will define the last validation which checks for whether the password or confirm password is equal or not.

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
//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');
    }
}

 

 

 

 

 

Full Javascript Code

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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);
});

Recent Posts

  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Android Java Project to Embed Google Maps & Add Markers Using Maps SDK
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme