我希望你能理解我的标题。
我不想在提交的表单中显示所有错误的列表,而是想在表单中的字段旁边显示它们:
这是我的代码的一小段:
$errors = array();
if (empty($subject)) {
$errors[] = $lang['Empty Subject'];
}
if (empty($category)) {
$errors[] = $lang['Empty Category'];
}
if (strlen($ath) > 255) {
$errors[] = $lang['Too Long'];
}
if (!validate_string($str)) {
$errors[] = $lang['Invalid String'];
}
and the list goes on...
用于显示:
if (!empty($errors)) {
foreach ($errors as $error)
$page['errors'] = array();
$page['errors'][] = '<li class="red"><span>'.$error.'</span></li>';
}
我知道我可以为每个错误设置一个变量,但这似乎不是一个明智的想法,比如,这会起作用,但看起来很愚蠢:
if (empty($subject)) {
$error_subject = $lang['Empty Subject'];
}
if (empty($category)) {
$error_category = $lang['Empty Category'];
}
然后在每个字段旁边:
Subject:
<input type="text" name="subject"><?php echo isset($error_subject) ? '<span style="color: red">'.$error_subject.'</span>' : '';
Category:
<input type="text" name="category"><?php echo isset($error_category) ? '<span style="color: red">'.$error_category.'</span>' : '';
然而,无论如何,一次只显示一个错误。
专业人士是如何做到这一点的?
动态创建输入
$inputs=array('subject','category'); //etc
foreach ($inputs as $input){
<input type="text" name="{$input}"><?php echo isset(${$error_.$input} ? '<span style="color: red">'.${$error_.$input}.'</span>' : '';
}