Question

I got a FormValidator class that I use to validate form inputs.

But what I want now is to check if there is only 1 input error. And if there is, it should add the autofocus attribute to only that input in the HTML. If there is more then 1 error, it should leave the empty string variables as is.

With my code I am just adding ' autofocus' to every input that's erroneous.

Anybody who could help me out to get it the way I described?

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>
Was it helpful?

Solution

.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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top