Form validation is done to check the accuracy of the user’s entered information before they could submit the form.
What validation checks in the form? It’s meant to check the following things:
- Check for Empty Field: Has the user left required field empty. If it’s there, returns alert message.
- Check for Numbers: User entered number in the text field where number is required, say in a Contact field.
- Check for Alphabets: Has the user entered characters in alphabets, say in name field.
- Check for Numbers and Letters: If a text input is all alphanumeric characters (numbers and letters), say in a message field
- Check for Characters: Has the user entered correct number of characters. (Useful when restricting the length of a username and/or password)
- Select for Drop Down List Item: If a selection has been made from HTML select input (the drop down selector)
- Email Validation: has the user entered valid email address.
To check, whether the user entered correct form of data, it’s must to apply form validation in any of the form. Here I am giving you the form validation codes in JavaScript. The codes contains some regular expression. These are simple meta characters which do pattern matching.
Regular Expression
Regular expression helps you in pattern matching in string.
. : Matches any single charcter except a new line
+ : Matches the preceding character or repeated character.
$ : Matches character at the end of the line.
.: Matches only period.
^ : Matches the beginning of a line or string.
: Escapes a special character.
- : Range indicator. [a-z, A-Z]
-: Escapes a special character.(e.g. escaping - by -)
[0-9] : It matches digital number from 0-9.
[a-z] : It matches characters from lowercase ‘a’ to lowercase ‘z’.
[A-Z] : It matches characters from uppercase ‘A’ to lowercase ‘Z’.
w: Matches a word character and underscore. (a-z, A-Z, 0-9, _).
W: Matches a non word character (%, #, @, !).
{M, N} : Donates minimum M and maximum N value.
Now, let’s dive deep into the codes. Checking for form completion: The first step of form validation is to check, whether the user have entered information in all the fields or not. If an user miss out any field, than the form will display error message. Validation codes will return an alert message, if it finds some empty fields in the form. That means, you could be very sure about the form, whether users have entered the details or not. If by mistake, user skips entering any detail, soon the alert message appear on the form. The codes for checking form empty fields are given below:
//This segment displays the validation rule for all field.
if(firstname.value.length == 0){
document.getElementById('head').innerText = "* All fields are mandatory *";
firstname.focus();
return false;
}
Checking for all Letters
There is an expression that checks whether the string contains only alphabets or not. The expression is: /^[a-zA-Z]+$/ The above expression checks whether the input characters in the string is alphabet or not. If the entered characters in the field is not in lower case or upper case. It will return a false value.
//This segment displays the validation rule for name text field.
function inputAlphabet(inputtext, alertMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(inputtext.value.match(alphaExp)){
return true;
}else{
document.getElementById('p1').innerText = alertMsg;
inputtext.focus();
return false;
}
}
Checking for all numbers
When it’s about checking contact field or zip code field, one need to check whether only the number have been entered or not. The basic expression for matching entered value as number in the field is: /^[0-9]+$/. If the string value is numeric, it will return true, otherwise it will return false.
//This segment displays the validation rule for zip code field.
function textNumeric(inputtext, alertMsg){
var numericExpression = /^[0-9]+$/;
if(inputtext.value.match(numericExpression)){
return true;
}else{
document.getElementById('p6').innerText = alertMsg;
inputtext.focus();
return false;
}
}
Checking for all numbers and letters
By combining the expression for numbers and alphabetic characters, there is an expression that checks, whether the entered things includes numbers and alphabetic character or not. The expression for matching numbers and characters in the field is: /^[0-9a-zA-Z]+$/
//This segment displays the validation rule for address field.
function textAlphanumeric(inputtext, alertMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(inputtext.value.match(alphaExp)){
return true;
}else{
document.getElementById('p5').innerText = alertMsg;
inputtext.focus();
return false;
}
}
Restricting the length
If you want to restrict the number of characters, the user enters into the field, than it’s better to restrict the length of the field.
//This segment displays the validation rule for username.
function lengthDefine(inputtext, min, max){
var uInput = inputtext.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
document.getElementById('p2').innerText = "* Please enter between " +min+ " and " +max+ " characters *";
inputtext.focus();
return false;
}
}
Right Selection made from drop-down
It’s must to provide validation in the select field. It happens sometimes, when user forgets to choose option from the select feild. In that case, the form should convey about issue so that user can take the action.
//This segment displays the validation rule for selection field.
function trueSelection(inputtext, alertMsg){
if(inputtext.value == "Please Choose"){
document.getElementById('p4').innerText = alertMsg;
inputtext.focus();
return false;
}else{
return true;
}
}
Email Validation
Firstly, let’s have a look how a user can make mistake while entering wrong email address:
- @compem.net [no character [email protected]]
- [email protected] [invalid character!]
- [email protected]_bright.com [underscore are not allowed in the domain name]
Now let’s see what a valid email address should contain:
- The combination of letters, numbers, periods, plus sign, and /or underscores.
- The @symbol.
- Combination of letters, numbers and periods.
- The top level domain. (com, net, org, us, gov)
So, just to make sure that user entered the email address in the correct format, it’s necessary to include email validation code inside the validation codes. A general expression to check valid email address is: /^[w-.+][email protected][a-zA-Z0-9.]+.[a-zA-Z0-9]{2,4}$/ The expression checks the letters, numbers, and other symbol at a proper sequence. The sequence is defined as: [alphabets/numbers/underscore/plus [email protected]/numbers/periods.domain name] If the entered email address is not in a proper sequence, then the message will popup which says “Wrong Email Address”.
//This segment displays the validation rule for E-mail.
function emailValidation(inputtext, alertMsg){
var emailExp = /^[w-.+][email protected][a-zA-Z0-9.-]+.[a-zA-z0-9]{2,4}$/;
if(inputtext.value.match(emailExp)){
return true;
}else{
document.getElementById('p3').innerText = alertMsg;
inputtext.focus();
return false;
}
}
Complete Form Validation Codes Using JavaScript
Here is a complete sequence of form validation codes. HTML File – formvalid.html
- Includes HTML form tags.
- onsubmit = return formValidation(). This means, formValidation() will be called as soon as user submit the form.
- The function will check the form details, whether the details are appropriate or not and then it alert messages if the user has entered wrong information or left any field empty.
<!DOCTYPE html>
<html>
<head>
<title>Form Validation:Demo Preview</title>
<meta content="noindex, nofollow" name="robots">
<link href="formvalid.css" rel="stylesheet">
<script src="formvalid.js"></script>
</head>
<body>
<div id="form">
<p id="head"></p>
<!-- This segment displays the validation rule -->
<h2>JavaScript Form Validation</h2>
<!-- Form starts from here -->
<form onsubmit='return formValidation()'>
<label>Full Name:</label>
<input id='firstname' type='text'>
<p id="p1"></p>
<!-- This segment displays the validation rule for name -->
<label>Username(6-8 characters):</label>
<input id='username' type='text'>
<p id="p2"></p>
<!-- This segment displays the validation rule for user name -->
<label>Email:</label>
<input id='email' type='text'>
<p id="p3"></p>
<!-- This segment displays the validation rule for email -->
<label>State:</label>
<select id='state'>
<option>
Please Choose
</option>
<option>
America
</option>
<option>
Australia
</option>
<option>
Sweden
</option>
<option>
Africa
</option>
</select>
<p id="p4"></p>
<!-- This segment displays the validation rule for selection -->
<label>Address:</label>
<input id='addr' type='text'>
<p id="p5"></p>
<!-- This segment displays the validation rule for address -->
<label>Zip Code:</label>
<input id='zip' type='text'>
<p id="p6"></p>
<!-- This segment displays the validation rule for zip -->
<input id="submit" type='submit' value='Check Form'>
</form>
</div>
</body>
</html>
JavaScript File – formvalid.js
- It includes various function to check validity of entered information.
- Like, formValidation() is the main function that runs as soon as the user clicks on submit button. Here, object is defined for each field. Objects are stored in different variable.
- Includes functions to check whether entered information in form is in correct format or not. This is done by regular expressions in each function. These regular expression matches the entered information in the form field. Function Calls -> Regular Expression matches data -> Wrong data pattern -> Display Alert Message.
function formValidation() {
// Make quick references to our fields.
var firstname = document.getElementById('firstname');
var addr = document.getElementById('addr');
var zip = document.getElementById('zip');
var state = document.getElementById('state');
var username = document.getElementById('username');
var email = document.getElementById('email');
// To check empty form fields.
if (firstname.value.length == 0) {
document.getElementById('head').innerText = "* All fields are mandatory *"; // This segment displays the validation rule for all fields
firstname.focus();
return false;
}
// Check each input in the order that it appears in the form.
if (inputAlphabet(firstname, "* For your name please use alphabets only *")) {
if (lengthDefine(username, 6, 8)) {
if (emailValidation(email, "* Please enter a valid email address *")) {
if (trueSelection(state, "* Please Choose any one option")) {
if (textAlphanumeric(addr, "* For Address please use numbers and letters *")) {
if (textNumeric(zip, "* Please enter a valid zip code *")) {
return true;
}
}
}
}
}
}
return false;
}
// Function that checks whether input text is numeric or not.
function textNumeric(inputtext, alertMsg) {
var numericExpression = /^[0-9]+$/;
if (inputtext.value.match(numericExpression)) {
return true;
} else {
document.getElementById('p6').innerText = alertMsg; // This segment displays the validation rule for zip.
inputtext.focus();
return false;
}
}
// Function that checks whether input text is an alphabetic character or not.
function inputAlphabet(inputtext, alertMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
} else {
document.getElementById('p1').innerText = alertMsg; // This segment displays the validation rule for name.
//alert(alertMsg);
inputtext.focus();
return false;
}
}
// Function that checks whether input text includes alphabetic and numeric characters.
function textAlphanumeric(inputtext, alertMsg) {
var alphaExp = /^[0-9a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
} else {
document.getElementById('p5').innerText = alertMsg; // This segment displays the validation rule for address.
inputtext.focus();
return false;
}
}
// Function that checks whether the input characters are restricted according to defined by user.
function lengthDefine(inputtext, min, max) {
var uInput = inputtext.value;
if (uInput.length >= min && uInput.length <= max) {
return true;
} else {
document.getElementById('p2').innerText = "* Please enter between " + min + " and " + max + " characters *"; // This segment displays the validation rule for username
inputtext.focus();
return false;
}
}
// Function that checks whether a option is selected from the selector and if it's not it displays an alert message.
function trueSelection(inputtext, alertMsg) {
if (inputtext.value == "Please Choose") {
document.getElementById('p4').innerText = alertMsg; //this segment displays the validation rule for selection.
inputtext.focus();
return false;
} else {
return true;
}
}
// Function that checks whether an user entered valid email address or not and displays alert message on wrong email address format.
function emailValidation(inputtext, alertMsg) {
var emailExp = /^[w-.+][email protected][a-zA-Z0-9.-]+.[a-zA-z0-9]{2,4}$/;
if (inputtext.value.match(emailExp)) {
return true;
} else {
document.getElementById('p3').innerText = alertMsg; // This segment displays the validation rule for email.
inputtext.focus();
return false;
}
}
CSS File – formvalid.css
- Includes form style codes.
@import url(http://fonts.googleapis.com/css?family=Raleway);
#main{
width:960px;
margin:50px auto;
font-family:raleway;
}
span{
color:red;
}
h2{
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 30px;
}
hr{
border:0;
border-bottom:1px solid #ccc;
margin: 10px -40px;
margin-bottom: 30px;
}
#form_layout{
width:300px;
float: left;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 25px;
margin-top: -2px;
}
input[type=text],input[type=password],#state{
width:99.5%;
padding: 10px;
margin-top: 8px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
}
input[type=submit]{
width: 100%;
background-color:#FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-bottom: 15px;
}
a{
text-decoration:none;
color: cornflowerblue;
}
i{
color: cornflowerblue;
}
p{
font-size:12px;
color:red;
}
Conclusion:
Above mentioned are simple codes for form validation. If you have any validation codes to share, please do share it in the below form.
11 Replies to “Form Validation Using JavaScript”
I pay a quick visit everyday some blogs and blogs to read content,
however this web site gives feature based posts.
Hello D.F. ,
Thank you so much for kind appreciation..!
Keep reading our other blog posts for getting more coding tricks.
Regards,
FormGet Team
Join Us On
Facebook : https://www.facebook.com/FormGet
Twitter : https://twitter.com/FormGetcom
Google Plus : https://plus.google.com/+Formget
It’s going to be end of mine day, but before ending I
am reading this impressive post to increase my experience.
Hello F. L. ,
Thanks for wonderful words.
Let us know if you have any suggestions and feedback.
Regards,
FormGet Team,
Join Us On
Facebook : https://www.facebook.com/FormGet
Twitter : https://twitter.com/FormGetcom
Google Plus : https://plus.google.com/+Formget
Hmm is anyone else having problems with the images on this blog loading?
I’m trying to figure out if its a problem on my end or
if it’s the blog. Any feed-back would be greatly appreciated.
Hello Christianity,
You can share your error here , I will have a review of it and let you know about the solution.
Regards,
FormGet Team.
There’s certainly a lot to find out about this subject.
I like all of the points you’ve made.
Hi,
Thanks for the impressive blog. I wanted to know here the paragraphs id’s are fixed. Can’t this code for textNumeric , inputAlphabet etc. be made generic. So that it is not specific to any one particular p id. So, that I can check multiple input fields. Because now, I have to define different functions for checking the different tags.
Create a web page that contains two text fields and a button labeled
Calculate. A user will enter his/her name and a number then click
Calculate button to get the result.
Use JavaScript to:
1. validate the inputs:
The name should contain only letters. If not, display alert
message “Not correct. Enter a valid name”
The user should enter a correct number. If not, display alert
message “Not correct. Please enter a Number”,
2. calculate the result:
The result is the sum from 1 to the entered number. For example, if the
entered number is 3, the result will be 10 (1+2+3= 6). When the user
clicks the Calculate button, the result should be displayed in a new
browser window, and written in green color.
The email regular expression is wrong:
var emailExp = /^[w-.+][email protected][a-zA-Z0-9.-]+.[a-zA-z0-9]{2,4}$/;
It should be:
var emailExp = /^[\w-.+][email protected][a-zA-Z0-9.-]+.[a-zA-z0-9]{2,4}$/;
What’s up, after reading this remarkable paragrapph i am as well
delighted to share my know-how here with mates.