如何自动聚焦唯一错误的输入字段?

时间:2014-04-20 09:59:21

标签: php html forms validation error-handling

我有一个FormValidator类,用于验证表单输入。

但我现在想要检查是否有仅1 输入错误。如果有,则应将autofocus属性添加到HTML中输入的 。如果有多于1个错误,则应该保留空字符串变量。

使用我的代码我只是添加'自动对焦'对每一个错误的输入。

有谁能帮助我按照我描述的方式来解决它?

PHP

$nameFocus     = '';
$emailFocus    = '';
$passwordFocus = '';

$validate = new FormValidator();
$validation = $validate->check();

if($validation->error('name'))     $nameFocus     = ' autofocus';
if($validation->error('email'))    $emailFocus    = ' autofocus';
if($validation->error('password')) $passwordFocus = ' autofocus';

HTML

<form method="post" action="">
    <div>
        <label>Name</label>
        <input type="text" name="name"<?=$nameFocus?>>
    </div>
    <div>
        <label>Email</label>
        <input type="text" name="email"<?=$emailFocus?>>
    </div>
    <div>
        <label>Password</label>
        <input type="text" name="password"<?=$passwordFocus?>>
    </div>
    <button>Submit</button>
</form>

1 个答案:

答案 0 :(得分:0)

.php

session_start()
$_SESSION['nameFocus'] = false;
$_SESSION['emailFocus'] = false;
$_SESSION['passwordFocus'] = false;

$validate = new FormValidator();
$validation = $validate->check();

if($validation->error('name')) $_SESSION['nameFocus'] = true;  
else if($validation->error('email')) $_SESSION['emailFocus'] = true;  
else if($validation->error('password')) $_SESSION['passwordFocus'] = true;

header('Location : ./my_form.php');

.html

 <?php session_start() ?>

<form method="post" action="">
    <div>
        <label>Name</label>
        <input type="text" name="name" autofocus="<?php echo $_SESSION['nameFocus'] ? 'on' : 'off'  ?>">
    </div>
    <div>
        <label>Email</label>
        <input type="text" name="email" autofocus="<?php echo $_SESSION['emailFocus'] ? 'on' : 'off'  ?>">
    </div>
    <div>
        <label>Password</label>
        <input type="text" name="password" autofocus="<?php echo $_SESSION['passwordFocus'] ? 'on' : 'off'  ?>">
    </div>
    <button>Submit</button>
</form>