1

I am trying to validate a form using javascript, but it goes straight to next page instead of alert when fields are empty.

<script type="text/javascript">
validateForm()  
{    
    valid = true;   
    if  
        (document.contactForm.name.value == "") 
    {
        alert("Please enter your Name.");   
        valid = false;  
    }   
    if (document.contactForm.Contact.value== "")
    {
        alert("Please enter your contact details");
        valid = false;
    }       
    return valid;
}
  <form name="contactForm" method="post" action="confirmation.html" 
        onsubmit="return validateForm()" >
    <table>
      <tr>
        <td align="right">Name:</td>
        <td align="left"><input type="text" size="40" name="name" id="name" 
                                onblur="return  validateForm();"/></td>
      </tr>
      <tr>
        <td align="right">Contact number:</td>
        <td align="left"><input type="text" name="Contact" id="Contact"  
                                onblur="return validateForm();"/></td>
      </tr>
      <tr>
        <td align="right">Address:</td>
        <td align="left"><TEXTAREA NAME=“txtremarks" size="255"></TEXTAREA></td>
                                                               </tr>
<tr>
  <td>submit here</td>
  <td><input type="submit" name="send" value="Submit" /></td>
</tr>
</table>
</form>

It should display the error instead

4
  • If you indent the code, don't put backticks around it. That's only for inline code. Commented Jul 5, 2014 at 10:30
  • Thanks in advance to all for taking time to reply Commented Jul 5, 2014 at 10:31
  • You're missing </script> at the end of the Javascript. Commented Jul 5, 2014 at 10:32
  • it is in the actual code, forgot to add it here. Commented Jul 5, 2014 at 10:36

3 Answers 3

2

The line:

validateForm()

should be:

function validateForm()

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

Don't forget to attach the validateForm method to the html form onsubmit event, that has to return true/false as well

<form onsumbit="return validateForm();">
...
</form>

Comments

0
<script>

function validateForm(theForm)
{


    if (theForm.elementname.value == "")
  {
    alert("please enter element name value");
    theForm.elementname.focus();
    return (false);
  }

  return true;

}

</script>

<form method="post" action="iaction.php" onsubmit="return validateForm(this)" >

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.