[英]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”的表單,在form1內,我有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>
使用zebra形式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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.