In this tutorial we will learn javascript validation without using any third party library. we will validate the simple form with 5 inputs fields.
Let’s start with simple steps
Step 1: Create a html file
Firstly we are going to create html file which contains a form with basic fields.
- first name
- last name
- password
Index.html
<form name="registerform" onsubmit="return onSubmitHandle()">
<div class="form-group">
<label>First Name</label>
<input
id="firstName"
type="text"
name="firstName"
class="form-control"
/>
</div>
<div class="form-group">
<label>Last Name</label>
<input
id="lastName"
type="text"
name="lastName"
class="form-control"
/>
</div>
<div class="form-group">
<label>Email</label>
<input
id="email"
type="text"
name="email"
class="form-control"
/>
</div>
<div class="form-group">
<label>Password</label>
<input
type="password"
name="password"
id="password"
class="form-control"
/>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input
type="password"
name="confirmPassword"
class="form-control"
/>
</div>
<div class="form-group">
<input type="submit" value="Submit" />
</div>
</form>
Step 2 : Create script file
We can use inline javascript or a separate javascript file. we will create 3 function.
- getElement : To find the input element in dom
- isEmpty : To check the input element is empty or not
- onSubmitHandler : To check the form validation on submit.
index.js
function getElement(id) {
return document.getElementById(id).value;
}
function isEmpty(id) {
if (getElement(id) == '') {
return true;
}
return false;
}
function ¸() {
var isFormValid = true;
if (isEmpty('firstName')) {
isFormValid = false;
alert('Please enter first name');
} else if (isEmpty('lastName')) {
isFormValid = false;
alert('Please enter last name');
} else if (isEmpty('email')) {
isFormValid = false;
alert('Please enter email');
} else if (isEmpty('password')) {
isFormValid = false;
alert('Please enter password');
}
return isFormValid;
}
Working live example and code