如何在 php 中验证表单


How to validate a form in php?

我知道如何在JavaScript中验证表单,但不知道如何在php中验证表单。这是我的代码:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Cafeteria Ordering System</title>
<style type="text/css">
@import "cafeteriastyle.css";
</style>
</head>
<body>
<?php
if(isset($_POST['btnSubmit']))
{
    //2nd page
}
else
{
?>
<form name="form1" method="post">
<table width="500" border="0" align="center" class="TableBorder">
  <tbody>
    <tr>
      <td colspan="2" align="center" class="TableTitle TableHeadingFill">Cafeteria Ordering System</td>
    </tr>
    <tr>
      <td width="250" align="right"><p>Customer ID</p></td>
      <td><input type="text" name="txtID"></td>
    </tr>
    <tr>
      <td align="right"><p>Num. Of Items Order</p></td>
      <td><input type="text" name="txtItems"></td>
    </tr>
    <tr>
      <td colspan="2" align="center"><input type="submit" name="btnSubmit"></td>
    </tr>
  </tbody>
</table>
</form>
<?php
}
?>
</body>
</html>

有一个表单调用"form1",在表单 1 中,我有 2 个文本字段。
单击"提交"按钮时,我想执行表单验证检查,以确保两个文本字段都已填充,然后跳转到第二页。如果文本字段为空,则显示警告消息并保持在同一页面上。
我知道如何用JavaScript做到这一点,例如:

<script language="javascript" type="text/javascript">
    function formValidation()
    {
        if(form1.elements["Name"].value.trim() == "")
        {
            alert("Please enter the name");
            form1.elements["Name"].select();
            return false;
        }
        return true;
    }
</script>

只需要将onSubmit="return formValidation"添加到表单标签中,例如:
<form name="form1" method="post" onSubmit="return formValidation()">那么它可能会起作用。但是如何使用php而不是JS来做到这一点呢?

<?php
if(isset($_POST['btnSubmit']))
{
    $txnid=trim($_POST['txtID']);
    $txtItems=trim($_POST['txtItems']);
    if(!empty($txnid) && !empty($txtItems))
    {
       //2nd page
    }
    else
    {
       echo 'Both Fields are Required.';
    }
}
else
{
?>
<form name="form1" method="post">
<table width="500" border="0" align="center" class="TableBorder">
  <tbody>
    <tr>
      <td colspan="2" align="center" class="TableTitle TableHeadingFill">Cafeteria Ordering System</td>
    </tr>
    <tr>
      <td width="250" align="right"><p>Customer ID</p></td>
      <td><input type="text" name="txtID"></td>
    </tr>
    <tr>
      <td align="right"><p>Num. Of Items Order</p></td>
      <td><input type="text" name="txtItems"></td>
    </tr>
    <tr>
      <td colspan="2" align="center"><input type="submit" name="btnSubmit"></td>
    </tr>
  </tbody>

使用斑马形式 http://stefangabos.ro/php-libraries/zebra-form/这是最好的将同时进行PHP和JS验证

将此检查与 jquery 一起使用可能会对您有所帮助

 function formValidation()
    {
        if($("input[name='name']").trim() == "")
        {
            alert("Please enter the name");
            $("input[name='name']").focus();
            return false;
        }
        return true;
    }

试试这个...

function formValidation()
    {
        if($("input[name='name']").val().trim() == "")
        {
            alert("Please Enter The Name");
            return false;
        }
        return true;
    }