Sunday, 17 February 2013

Contact form – required fields check with JavaScript

Below is a simple JavaScript to add to your contact form when you need to check if the required fields are empty. The script will not only check but will focus required/empty field.

The form:

#form fieldset.normal label{width: 10em;display:block; float:left;}
<form id="form" action="" method="post" name="form" onsubmit="return validateForm(form);"
  <fieldset class="normal">
    <label for="FirstName">First Name *</label><input type="text" name="FirstName" size="40" /><br/>
    <label for="LastName">Last Name *</label><input type="text" name="LastName" size="40" /><br/>
    <label for="EmailAddress">Email Address *</label><input type="text" name="EmailAddress" size="40" /><br/>
        <label for="Message">Message *</label><textarea cols="40" name="Message" rows="10"></textarea><br/>
<input type="submit" value="submit" />

The script:

<script type="text/javascript" language="javascript">
function validateForm(thisform){
 if(thisform.FirstName.value=="") {
   alert("Please enter your First Name.");
   return false;
 if(thisform.LastName.value=="") {
   alert("Please enter your Last Name.");
   return false;
 if(thisform.EmailAddress.value=="") {
   alert("Please enter your Email Address.");
   return false;
if(thisform.Message.value=="") {
   alert("Please enter your Message.");
   return false;

And here is the script in action doing the checks in the form:

Thanks to Stuart McMath for cleaning up and enhancing the script code.

No comments:

Post a Comment