php - 为什么我的 PHP 错误消息不能正常工作?
问题描述
我正在创建一个基本表格来购买成人和儿童票。通过表单的设置方式,用户必须购买成人票,但不需要购买儿童票。我添加了一些错误消息/验证以在表单中强制执行规则。所有成人票错误消息都可以正常工作,但儿童票错误消息无法正常工作。
我希望儿童票规则检查以下内容:输入了有效数字(也不是字母),数量大于 0,并且输入了整数。我以为我已经设置了规则,所以他们只在子票输入不为空时才开始验证,但他们仍在尝试验证何时为空,考虑到没有子票需要,我不希望它这样做被购买。我怎样才能让它正常工作?
这是我的带有错误消息的 PHP 代码。
<?php
$adult=$_POST['adult'];
$child=$_POST['child'];
$date=date('m/d/Y');
function isInteger($input) {
return(ctype_digit(strval($input)));
}
if (empty($adult)) {
$error_message='You must purchase at least 1 Adult ticket!';
}
else if (!is_numeric($adult)) {
$error_message="You must enter a valid number!";
}
else if ($adult <= 0) {
$error_message="You must enter a quantity greater than zero!";
}
else if (!isInteger($adult)) {
$error_message="You must enter a whole number for the quantity! (i.e. 1, 2, etc...)";
}
else if (!empty(!is_numeric($child))) {
$error_message="You must enter a valid number!";
}
else if (!empty($child <= 0)) {
$error_message="You must enter a quantity greater than zero!";
}
else if (!empty(!isInteger($child))) {
$error_message="You must enter a whole number for the quantity! (i.e. 1, 2, etc...)";
}
else if ($adult + $child > 5) {
$error_message="Sorry, there is a limit of 5 total tickets per customer!";
}
else {
$error_message='';
}
if($error_message !=""){
include('index.php');
exit();
}
?>
解决方案
如果$child = 1
if(!empty($child <= 0) )
相当于if(!empty(false))
which 没有意义。
与(!empty(!is_numeric($child)))
if(isset($child) && $child <= 0) {}
改为使用
你也可以使用$child = isset($_POST['child']) ? $_POST['child'] : 0
推荐阅读
- node.js - 使用每个数组的长度将 3 个数组合并为一个数组
- excel - 索引/匹配以返回匹配条件的结果列表
- angular - 如何使用可观察的角度进行一致的http调用?
- python - 多页 Dash 应用回调未注册
- firebase - 如何在 Vuexfire 中使用 Moment.js
- rest - 用于传入整数数组的正确的rest uri格式?
- json - @RequestBody 不适用于 @JsonProperty
- entity-framework - Entity Framework Core:在 SQL 中生成重复的列名
- html - 防止在表格内调整图像大小(表格在另一个单元格内)
- node.js - 出现错误:“url”参数必须是字符串类型。尝试发布到 Heroku 上托管的 Slack 机器人时收到类型未定义