您好我正在尝试使用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>
答案 0 :(得分:1)
您可以使用floatval
函数来获取变量的浮点值,然后检查它是否为浮点值,如下所示:
if(is_float(floatval($price))){
echo "float value";
}else{
echo "not a float value";
}
<强>编辑:强>
在您的代码中,您可以执行以下操作:
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(floatval($price))){
$priceErr = "Invalid input, only doubles allowed.";
}