Javascript Essentials Part 4


Form Validation

By simple body and head section script method

Put the following script in body section. On hitting submit button, form returns function CheckData which validates input fields.

<form name="quickmessage" action="somepage.php" method="POST" onSubmit="return CheckData()">
<input name="name" type="text" class="formsecond" id="name">
<input name="email" type="text" class="formsecond" id="email">
<input name="phone" type="text" class="formsecond" id="phone">
<textarea name="message" rows="5" class="formsecond2" id="message"></textarea>
<input name="Submit2" type="reset" class="button" value="Reset"> 
<input name="Submit3" type="submit" class="button" value="Submit">
</form>

Put the following script in head section of web page.

<script language="javascript">
function isValidEmail(str) {
return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}
function CheckData()
{
with(document.quickmessage)
{
if(name.value == "")
{
alert("Please enter your name.");
name.focus();
return false;
}
if(email.value == "")
{
alert("Please enter your email address.");
email.focus();
return false;
}
if (!isValidEmail(email.value)) 
{
alert("Please enter a valid email address");
return false;
}
if(phone.value == "")
{
alert("Please enter your phone number.");
phone.focus();
return false;
}
if(message.value == "")
{
alert("Please enter Message/Query.");
message.focus();
return false;
}
}
return true;
}
</script>
By external js validator file

Following example uses an external js file to validate form input fields.

Download Form Validation Method

Related Posts


1 thought on “Javascript Essentials Part 4

Leave a Reply

Your email address will not be published. Required fields are marked *