只是一個快速的,我似乎無法發現,並希望其他人可以發現我的錯誤,我有一些PHP編寫的字符串驗證代碼,我遇到的問題是表單似乎在打開提交按鈕後立即驗證「customerfname」字段,只要表單打開,即使在按下提交按鈕之前也會顯示錯誤「請輸入您的名字」。有誰能發現我的錯誤?提交之前表單驗證
<?php
$flag = false;
$badchar = "";
$string = $_POST["customerfname"];
$string = trim($string);
$length = strlen($string);
$strmsg = "";
if (isset($_POST["submit"])) {
if ($length == 0) {
$strmsg = '<span class="error"> Please enter your first name</span>';
$flag = true;
$valid = false;}
else if ($length > 30) {
$strmsg = '<span class="error"> Can not enter more than 30 characters</span>';
$flag = true;
$valid = false;
}
else{
for ($i=0; $i<$length;$i++){
$c = strtolower(substr($string, $i, 1));
if (strpos("abcdefghijklmnopqrstuvwxyz-", $c) === false){
$badchar .=$c;
$flag = true;
$valid = false;
}
}
if ($flag) {
$strmsg = '<span class="error"> The field contained the following invalid characters: '.$badchar.'</span>';}
}
if (!$flag) {
$valid = true;
}
}
?>
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="custinfo">
<td><label for="customerfname">Customer First Name: </label></td>
<td><input type="text" id="customerfname" name="customerfname" size=50/><?php echo $strmsg; ?></td>
<p><input type="submit" name="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</form>
學習正則表達式,你不會後悔的。 – elclanrs
嘗試過,沒有問題...我注意到沒有發送$ _POST ['submit'],但是甚至沒有輸入驗證碼。 –
你沒有提交按鈕? – Kuzgun