Form Validation

Code 1:

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["mname"].value;
var z=document.forms["myForm"]["lname"].value;
var a=document.forms["myForm"]["email"].value;
var atpos=a.indexOf("@");
var dotpos=a.lastIndexOf(".");

if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }

if (y==null || y=="")
  {
  alert("Middle name must be filled out");
  return false;
  }

if (z==null || z=="")
  {
  alert("Last name must be filled out");
  return false;
  }

if (a==null || a=="")
  {
  alert("Email must be filled out");
  return false;
  }
  else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=a.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }

}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname"><br>
Middle name: <input type="text" name="mname"><br>
Last name: <input type="text" name="lname"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>

</html>


Form Validation in JavaScript


Code 2:


<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["mname"].value;
var z=document.forms["myForm"]["lname"].value;
var a=document.forms["myForm"]["email"].value;
var atpos=a.indexOf("@");
var dotpos=a.lastIndexOf(".");

if ((x==null || x=="") || (y==null || y=="") || (z==null || z=="") || (a==null || a=="") ) {
alert("Some data is missing please fill all the boxes");
return false;
}
  else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=a.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }
  else{
  alert ("Welldone you have completed your task ");
  }

}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<br>Middle name: <input type="text" name="mname">
<br>Last name: <input type="text" name="lname">
<br>Email: <input type="text" name="email">
<br><input type="submit" value="Submit">
</form>
</body>


</html>


Comments