我对我的表单进行了这么长时间的验证,除了对价格的验证外,一切似乎都要检查,以确保它是正确的格式,基本上是一系列数字后跟一个小数点和另外2个数字即12.00或112.00或124.53等。
这是我的代码,它还检查字段是否已设置且不为空,以及产品名称是否已存在。
<?php
if(isset($_POST['submit']) && isset($_POST['product-name']) && !empty($_POST['product-name']) && isset($_POST['description']) && !empty(trim($_POST['description'])) && isset($_POST['price']) && !empty($_POST['price']) && isset($_POST['category']) && !empty($_POST['category']) && isset($_POST['spice']) && !empty($_POST['category']) && isset($_POST['date-added']) && !empty($_POST['date-added'])){
$product_name = trim($_POST['product-name']);
$description = trim($_POST['description']);
$price = $_POST['price'];
$category = $_POST['category'];
$spice = $_POST['spice'];
$date_added = $_POST['date-added'];
$pattern = '/^\d+(?:\.\d{2})?$/';
$pattern1 = '/^([1-9][0-9]*|0)(\.[0-9]{2})?$/';
if(preg_match($pattern, $price)){
$error = "<script language='javascript'>
window.onload = function(){
var divs = document.getElementById('error');
divs.innerHTML = '<p style = \"color:#FF0000\">Price is in the wrong format, correct format e.g. 10.00</p>';
}
</script>";
}
if(!isset($error)){
$rows = getProductName($product_name);
if($rows > 0){
echo "<script language='javascript'>
window.onload = function(){
var divs = document.getElementById('error');
divs.innerHTML = '<p style = \"color:#FF0000\">Product name already exists!</p>';
}
</script>";
} else{
insertProduct($product_name, $description, $price, $category, $spice, $date_added) ;
echo "<script language='javascript'>
window.onload = function(){
var divs = document.getElementById('error');
divs.innerHTML = '<p style = \"color:#FF0000\">Record Inserted Successfully!</p>';
}
</script>";
}
} else{
echo $error;
}
} else{ echo "<script language='javascript'>
window.onload = function(){
var divs = document.getElementById('error');
divs.innerHTML = '<p style = \"color:#FF0000\">Please fill out all required (*) fields!</p>';
}
</script>";
}
?>
这很可能是简单的事情,但我似乎无法看到问题所在。
表单太长但是这是一个包含字段的精简版本:†
<form method="post" action="addProduct.php">
<ul class="form-style-1">
<div id="error"></div>
<h2>Add Product</h2>
<li> <label>Price: <span class="required">*</span></label> <input type="text" name="price" class="field-long" placeholder="Enter Price" /> </li>
</form>
† 在2017-03-10 03:06:52Z
上添加了对Hydra answer的评论答案 0 :(得分:0)
我认为您忘了!exclamation mark
,因为您要确定您的值是否与特定模式匹配:
if(!preg_match($pattern, $price))
如果值为float,您还可以使用返回is_float()
的{{1}}函数,否则它将返回true