嗨,我想驗證用戶輸入的表單使用PHP。 我已經設法驗證文本,數字和年份輸入,但無法獲得工作價格。驗證'價格'(雙)表單輸入PHP
我在我的代碼的頂部創建誤差變量:
$titleErr = ""; $developerErr = ""; $releaseErr = ""; $stockErr = ""; $priceErr = "";
我然後驗證輸入並分配消息發送到所述可變如果需要的話:
if (!preg_match("/^[a-zA-Z ]*$/",$title)) {
$titleErr = "Invalid input, only letters and white space allowed.";
} else if (!preg_match("/^[a-zA-Z ]*$/",$developer)){
$developerErr = "Invalid input, only letters and white space allowed.";
} else if ($release<1990 || $release>2020){
$releaseErr = "Invalid input, enter a year between 1990 & 2020.";
} else if (!is_numeric($stock)){
$stockErr = "Invalid input, only numbers allowed.";
} else if (!is_float($price)){
$priceErr = "Invalid input, only doubles allowed.";
}
前4個語句驗證完美輸入。然而,最後一個檢查輸入是否爲浮點數(價格例如10.99)似乎會在輸入正確的輸入時返回錯誤消息。
這是我的形式:
<form class ="form-horizontal" role="form" id="add" name="add" action="?" method="post">
<div class="form-group">
<label class="control-label col-sm-2">Title</label> <div class="col-sm-10"><input class="form-control" id="addFormTitle" name="title" type="text"> <span class="error"><?php echo $titleErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Developer</label> <div class="col-sm-10"><input class="form-control" id="addFormDeveloper" name="developer" type="text"> <span class="error"><?php echo $developerErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Release (Year Format/YYYY)</label> <div class="col-sm-10"><input class="form-control" id="addFormRelease" name="release" type="text"> <span class="error"><?php echo $releaseErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Stock</label> <div class="col-sm-10"><input class="form-control" id="addFormStock" name="stock" type="text"> <span class="error"><?php echo $stockErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Price (£)</label> <div class="col-sm-10"><input class="form-control" id="addFormPrice" name="price" type="text"> <span class="error"><?php echo $priceErr;?></span></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" name="addSubmit" value="Add product">Submit</button>
</div>
</div>
</form>
當您的瀏覽器向PHP發送值(例如,使用GET或POST),**所有**都被PHP解釋爲一個字符串。即使該值爲'1',這實際上是「1」。因此使用'is_float()'將永遠是錯誤的。 – Mike
檢查出[驗證價格]的正則表達式(http://stackoverflow.com/a/4983648/5509627) – Tristan