验证更新表单

时间:2012-09-21 04:29:35

标签: php javascript validation

我正在创建一个页面,其中我从表中获取数据并在文本框中显示数据以允许用户更新记录。我还验证了文本框的用户输入。但问题是当用户没有更改任何字段并点击提交时,它会验证用户名字段,即它总是想要更改(或编辑文本框)文本框的值。

这是我的代码:

<?php
include("conn.php");
$id=$_GET['id'];
$sql="SELECT * FROM test WHERE id='$id'";
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
?>

<script type='text/javascript'>
function formValidator()
{
    // Make quick references to our fields
    alert("hiiiiiii");
    var name = document.getElementById('name').value;
    var email = document.getElementById('emailid').value;
    var ph = document.getElementById('ph').value;

    if( name=="" || name==null)
     {
         alert("Please Enter user name");
         return false;
     }
     var alphaExp = /^[a-zA-Z]+$/;
     if(!name.match(alphaExp))
      {
          alert("please Enter only Alphabates for Name");
          return false;
      }

      if(email=="" || email=="null")
      {
          alert("Please Enter Email Address");
          return false;
      }
      var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
      if(!email.match(emailExp))
       {
           alert("please Enter valide email address");
            return false;
       }
       if(ph=="" || ph=="null")
       {
           alert("Please Enter Phone Number");
           return false;
       }
       var numericExpression = /^[0-9]+$/;
       if(!ph.match(numericExpression))
       {
           alert("Enter only Digit for Phone Number");
           return false;
       }
}
</script>


<form name="updateform" method="POST" action="update_ind_new.php" onsubmit='return formValidator()'>
  <table width="200" border="0">
    <tr>
     <td>User Name</td>
      <td>E-Mail</td>
       <td>phno</td>
     </tr>
    <tr>
    <td><label>
        <input name="name" type="text" id="name" value=" <?php echo $row['name']; ?>" >
      </label></td>
      <td><label>
        <input name="email" type="text" id="emailid" value=" <?php echo $row['emailid']; ?>" >
      </label></td>
      <td><label>

        <input name="ph" type="text" id="ph" value=" <?php echo $row['phno']; ?>" >
      </label></td>

    </tr>
    <tr>
      <td> <input name="id" type="hidden" id="id" value=" <?php echo $row['id']; ?>"></td>
      <td><label>
        <input type="submit" name="Submit" value="Submit">
      </label></td>
      <td>&nbsp;</td>
    </tr>
  </table>
</form>

2 个答案:

答案 0 :(得分:2)

在此行的末尾写下return true;

   if(!ph.match(numericExpression))
   {
       alert("Enter only Digit for Phone Number");
       return false;
   }
   return true;

答案 1 :(得分:1)

return true;置于验证函数

中所有条件的末尾

或在“if else if else”条件下进行验证