drxnfdx798517235 2015-03-01 22:44
浏览 32

在不为每个输入字段设置变量的情况下在不同位置显示表单的错误

I hope you understand my title.

Instead of displaying a list of all the errors with the submitted form, I would like to show them beside the fields in the form:

This is a short snippet of my code:

$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...

And for displaying:

if (!empty($errors)) {
foreach ($errors as $error)
$page['errors'] = array();
    $page['errors'][] =  '<li class="red"><span>'.$error.'</span></li>';
}

I know I could set a variable for every error but that does not seem like a smart idea like, this would work but it seems so stupid:

if (empty($subject)) {
    $error_subject = $lang['Empty Subject'];
}

if (empty($category)) {
    $error_category = $lang['Empty Category'];
}

and then beside every field:

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>' : '';

However that does only show 1 error at a time anyways.

How do pros do this?

  • 写回答

1条回答 默认 最新

  • douwaif22244 2015-03-01 22:56
    关注

    create the inputs dynamically

    $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>' : '';
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大