Hi, first of all sorry if this has come up before, but I couldn't find it anywhere.

I have a working php form which submits data on submit. I need to verify the input fields to ensure they are not empty. I know i need a javascript function to run this check.

I am just having problems running the javascript before the form is submitted.

Any helps would be grand.

Javascript code:

<script language="JavaScript" type="text/javascript">
<!--
function verify ( form )
{
  if (form.email.value == "") {
    alert( "Please enter your email address." );
    return false ;
  }
else {
      return true ;
     }
}
//-->
</script>

Here is some of the code, with one of the required fields, email.

<form method="post" name="Comment Form" action="PHP/comment.php" target="_self">

<table border="0" name="pageid" id="commentform">

<tr>
    <td><div align="right">Email: (Required)</div></td>
    <td><input type="text" name="email" size="30" /></td>
</tr>

<tr>
<td>&nbsp;</td>
    <td>
    <input type="submit" name="submit" value="Submit" /> 
    <input type="reset" name="reset" value="Reset" />
    </td>
</tr>

</table>
</form>

Below i modified your script and now it check for null value.

<html>
<head>
<script language="JavaScript" type="text/javascript">
function verify ( form )
{
  if (form.email.value == "") {
    alert( "Please enter your email address." );
    return false ;
  }
else {
      return true ;
     }
}

</script>
</head>
<body>

<form method="post" name="Comment Form" action="PHP/comment.php" target="_self" onsubmit="return verify(this)">
 
<table border="0" name="pageid" id="commentform">
 
<tr>
    <td><div align="right">Email: (Required)</div></td>
    <td><input type="text" name="email" size="30" /></td>
</tr>
 
<tr>
<td>&nbsp;</td>
    <td>
    <input type="submit" name="submit" value="Submit" /> 
    <input type="reset" name="reset" value="Reset" />
    </td>
</tr>
 
</table>
</form>
</body>
</html>

You have to call verify function on onSubmit event of form.

You can also use php validation for null value checking and email validation.

-keval

I have done this, but it is still posting blank data. I'm not sure how, but the php script is still running first and the javascript is being ignored

First you check your browser support javascript or it is enable in browser settings.

You make simple javascript function that display alert for checking javascript is working and call function on button' s onClick event.

-keval

Member Avatar for rajarajan2017

The code given by keval_hack working perfectly.

Yeah, sorry guys, I'd made a stupid mistake (typo :( ).

It does work fine! Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.