Site icon FahmidasClassroom

Simple form validation using HTML and JavaScript

Capture

Form validation is an essential part of any type of web project. JavaScript is a good choice to validate any form before submit because it doesn’t reload the page. This tutorial will help the reader to learn the basic form validation by using JavaScript. Follow the following steps to complete the tutorial.

Steps:

1. Create a html file named userReg.html and add the following code.


<html>
<head>
<title>User Registration Form</title>
</head>
<body>
<br/><br/>
<center>
<table width="587" bgcolor="#CFE7E7">
<tr bgcolor="#00FFFF">
<td colspan="4" align="center"><h4>USER REGISTRATION FORM</h4></td>
</tr>
<tr>
<td colspan="2">&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td width="48">&nbsp;</td>
<td width="132">Name</td>
<td width="210"><input type="text" size="35" id="name" ></td>
<td width="177"><div id="msg1"></div></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>Gender</td>
<td><input type="radio" name="radio" id="radio1" value="radio" checked>
Male
<input type="radio" name="radio" id="radio2" value="radio">
Female</td>
<td><div id="msg2"></div></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>Email</td>
<td><input type="text" size="35" id="email" ></td>
<td><div id="msg3"></div></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>Phone</td>
<td><input type="text" size="35" id="phone" ></td>
<td><div id="msg4"></div></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>Username</td>
<td><input type="text" size="35" id="username" ></td>
<td><div id="msg5"></div></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>Password</td>
<td><input type="password" size="35" name="password" id="password" ></td>
<td><div id="msg6"></div></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>Confirm Password</td>
<td><input type="password" size="35" id="cpassword" ></td>
<td><div id="msg7"></div></td>
<tr>
<td colspan="4" align="center">&nbsp;</td>
</tr>
<tr>
<td colspan="4" align="center"><input type="button" name="button" id="button" value="Submit"></td>
</tr>
</table>
</center>
</body>
</html>

2. Declare a global variable named error to identify any error occurs or not and create a JavaScript function named sendMessage to set the helping text for the user.


<script>
var err1,err2,err3,err4,err5,err6,err7=false;
function sendMessage (divid, msg)
{
	if(err1!=true && err2 != true && err3 != true && err4 != true && err5 != true && err6 != true && err7 != true)
	document.getElementById(divid).innerHTML = "<font color='green'>"+msg+"</font>";
}
</script>

3. Set the following helping messages for the corresponding text fields.


onFocus="sendMessage('msg1','Type your fullname')"
onFocus="sendMessage('msg3','Type a valid email address')"
onFocus="sendMessage('msg4','Type valid phone numer')"
onFocus="sendMessage('msg5','Type a username between 6 to 12 characters' )"
onFocus="sendMessage('msg6','Type a password between 6 to 15 characters')"
onFocus="sendMessage('msg7','Type same password for confirmation')"

[***Note: if you don’t understand where you need to add the lines then you can check the video link given below.]

4. Call the function, sendMessage with empty message on onBlur event to remove the after losing the focus.


onblur="sendMessage('msg1','')"
onBlur="sendMessage('msg3','')"
onBlur="sendMessage('msg4','')"
onBlur="sendMessage('msg5','')"
onBlur="sendMessage('msg6','')"
onBlur="sendMessage('msg7','')"

5. Declare two functions named checkError and checkEmpty with the following code to give the message for required fields.


function checkError(elementID,divid,msg)
{
	if(document.getElementById(elementID).value == "")
	{
		document.getElementById(elementID).style.borderColor="red";
		document.getElementById(divid).innerHTML=msg;
		err1 = true
	}
	else
	{
		document.getElementById(elementID).style.borderColor="black";
		document.getElementById(divid).innerHTML="";
		err1=false;
	}
}
function checkEmpty()
{
	var error=false;
	error=checkError("name","msg1","This field can not be empty");
	error=checkError("email","msg3","This field can not be empty");
	error=checkError("phone","msg4","This field can not be empty");
	error=checkError("username","msg5","This field can not be empty");
	error=checkError("password","msg6","This field can not be empty");
	error=checkError("cpassword","msg7","This field can not be empty");
	if (error == false)
		alert("Validation successful");
  	else
		  alert("Invalid data exist");
}

6. Call the function when submit button is clicked.


onClick="checkEmpty()"

7. Name and email fields can’t contain number. Declare a function named checkEntryError to check the entry value of these fields are all characters not number.


function checkEntryError(eleid)
{
	if(!isNaN(document.getElementById(eleid).value) )
	{
		document.getElementById(eleid).style.borderColor="red";
		return true
	}
	else
	{
		document.getElementById(eleid).style.borderColor="black";
		return false
	}
}

8. Call the above function from checkError function with the following code.


if(elementID=="name" || elementID=="username")
err2=checkEntryError(elementID);

9. Call the checkError function on onChange event of name and username fields.


onchange='checkError("name","msg1","");'
onchange='checkError("username","msg5","");'

10. Create function named checkEmail to validate the email


function checkEmail(eleid) 
{
     if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById(eleid).value))
     {
	      document.getElementById(eleid).style.borderColor="black";
             return false
     }
     else
    {
             document.getElementById(eleid).style.borderColor="red";
             return true
     }
}

11. Phone field can’t contain character. Declare a function named checkPhnError to check the entry value of this field is all numbers.


function checkPhnError(eleid)
{
	if(isNaN(document.getElementById(eleid).value) )
	{
		document.getElementById(eleid).style.borderColor="red";
		return true
	}
	else
	{
		document.getElementById(eleid).style.borderColor="black";
		return false
	}
}

12. Call the above function from checkError function with the following code.


if(elementID=="phone")
	err3=checkPhnError(elementID)
		
if(elementID=="email")
	err4=checkEmail(elementID) 

if(elementID=="username")
{
 	var un = document.getElementById("username").value;
	if(un.length <6 || un.length>12 || checkEntryError(elementID))
	{
		document.getElementById("username").style.borderColor="red";
		err5=true
	}
	else
	{
		document.getElementById("username").style.borderColor="black";
		err5=false
	}
}

13. Call the checkError function on onChange event of phone field.


onchange='checkError("phone","msg4","");'
onchange='checkError("email","msg3","");'

14. Add the validation code for password and confirm password fields.


if(elementID=="password" || elementID=="cpassword")
{

	var pass = document.getElementById("password").value;
	if(pass.length <6 || pass.length>15)
	{
		document.getElementById("msg6").innerHTML="Password is not in correct format";
		document.getElementById("password").style.borderColor="red";
		err6=true
	}
	else
	{
		document.getElementById("msg6").innerHTML=" ";
		document.getElementById("password").style.borderColor="black";
		err6=false;
	}
	if(document.getElementById("password").value != "" && document.getElementById("cpassword").value != "" &&&& err6!=true)
	{

		if(document.getElementById("password").value != document.getElementById("cpassword").value )
		{
			document.getElementById("msg6").innerHTML="Password and Confirm password are not same";
			document.getElementById("password").style.borderColor="red";
			document.getElementById("cpassword").style.borderColor="red";
			err7=true
		}
		else
		{
			document.getElementById("msg6").innerHTML=" ";
			document.getElementById("password").style.borderColor="black";
			document.getElementById("cpassword").style.borderColor="black";
			err7=false;
		}
	}
	if (err1==true || err2==true || err3==true || err4==true || err5==true || err6==true || err7==true)
		return true;
	else
		return false
}

14. Call the checkError function on onChange event of password and cpassword fields.


onchange='checkError("password","msg6","");'
onchange='checkError("cpassword","msg7","");'

15. All validations are completed.

The steps of this tutorial are shown in the following video link.

Exit mobile version