Step 1:- Create a simple html form by use of code provided below:
<head>
<title>JavaScript Form Validation</title>
<script src = "javascript.js" language="javascript" type= "text/javascript"></script>
</head>
<body>
<form action="" name="Form" onsubmit="return(formvalidate());">
<table cellspacing="2" cellpadding="2">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">Email</td>
<td><input type="text" name="Email" /></td>
</tr>
<tr>
<td align="right">Pin Code</td>
<td><input type="text" name="Pin" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="" selected>Select Country</option>
<option value="1">USA</option>
<option value="2">JAPAN</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
<html>
Step 2:- Now create one Javascript.js file and put the below code inside that file.
function formvalidate()
{
if( document.Form.Name.value == "" )
{
alert( "Please insert your name." );
document.Form.Name.focus() ;
return false;
}
if( !validateEmail())
{
alert( "Please insert your Email address." );
document.Form.Email.focus() ;
return false;
}
if( document.Form.Pin.value == "" ||isNaN( document.Form.Pin.value ) )
{
alert( "Please insert the pin code." );
document.Form.Pin.focus() ;
return false;
}
if( document.Form.Country.value == "" )
{
alert( "Please select your country!" );
return false;
}
return( true );
}
function validateEmail()
{
var emailID = document.Form.Email.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
return false;
}
return( true );
}


0 comments:
Post a Comment