1

I want to build a simple server-side validation and I have a problem:

When the user submits the data and it is not correct, I want to keep the correct data into the input(example: if I have two fields, username and email, but only the email is not valid, the username should be saved).

In the following code I tried to create the attribute value only if the variable $validUser was initialized. Otherwise, I do not want a value attribute. The code is not working.

   <input type="text" placeholder="Username" name="username" id="username"
                   <?php
                      if ($validUser) echo "value='$validUser'";
                   ?>
    />

What should I do?

Bacchus
  • 515
  • 8
  • 22

1 Answers1

0

When the user submits the data...

Do you mean there's a $_POST or $_GET request? If so, this would make a little more sense

<input id="username"
       name="username"
       placeholder="Username"
       value="<?php echo isset($_GET['username']) ? $_GET['username'] : '' ?>">

If $_GET['username'] isn't present, you will just get value="" which is perfectly fine


Writing HTML via PHP by hand is a total chore. To combat this, I've written a utility called htmlgen which makes it quite a bit more tolerable

<?php
use function htmlgen\html as h;

h('input#username', [
  'name'=>'username',
  'placeholder'=>'Username',
  'value'=>isset($_GET['username']) ? $_GET['username'] : ''
]);

// => <input id="username" name="username" placeholder="Username" value="someuser">
Mulan
  • 129,518
  • 31
  • 228
  • 259