Home  • Programming • JavaScript

Input validating a HTML form with JavaScript Regular Expression

608
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JavaScript Form Input Validation</title><br>


<script type="text/javascript">

function isValidForm(f,container){
	 
	  error=[];
	  
	  if(!nameValidate(f.txtName.value)){
		  
		  error.push("Invalid Name!");
	  }
	  
	  if(!phoneValidate(f.txtPhone.value)){
		  
		  error.push("Invalid phone number!");
	  }
	  
	  if(!emailValidate(f.txtEmail.value)){
		  
		 error.push("Invalid Email Address!");
	  }
	  
	  if(!passwordValidate(f.pwdPassword.value,f.pwdRePassword.value,6)){
		  
		 error.push("Invalid Password!");
	  }
	  
	  
	  if(error.length>0){
		  
		  all_error="";
		  for(i=0;i<error.length;i++){
			  all_error+=error[i]+"<br/>";
		  }
		  
		  tag=document.getElementById(container);
		  tag.innerHTML=all_error;
		  tag.style.color="red";
		  return false;
	      
	  }
	  
	  
	  return true;
	
}



//---------------internal library functions---------------//
function nameValidate(name){
	 

  var patt=/^[a-zA-Z ]{3,}$/;
  var result=patt.test(name);
  return result;
 }
   
function phoneValidate(phone){
	 

  var patt=/^[0-9]{8,}$/;
  var result=patt.test(phone);
  return result;
	 
 }
 

 
function passwordValidate(password,retype_password,len){
		 
    if((password===retype_password) && (password.length>=len)){
		return true;
	}else{
		return false;
    }
 }
 
 
 function emailValidate(email){
	
   var patt=/^[a-zA-Z]+[.]?[a-zA-Z0-9]*[@][a-zA-Z]{2,}[.][a-zA-Z]{2,}$/;
   var result=patt.test(email);
    
	return result;
  
 } 

</script>

</head>

<body>
<form name="frmSignup" action="#" method="post" onSubmit="return isValidForm(this,'error')" style="width:400px; margin:0px auto;">
<div id="error"></div>
Name:<br><input type="text" name="txtName"><br>
Phone:<br><input type="text" name="txtPhone"><br>
Email:<br><input type="text" name="txtEmail"><br>
Password:<br><input type="password" name="pwdPassword"><br>
Retype Password:<br><input type="password" name="pwdRePassword"><br>
<input type="submit" value="Submit" name="btnSubmit">
</form>
</body>
</html>

Comments 4


Good Tutorial
Yes very good.
Happy
valuable
Copyright © 2025. Powered by Intellect Software Ltd