开发者

keep User Information in form in case of errors

How do i keep the information a user has entered in a form in a case where s/he has made an error in the 开发者_运维问答form so that s/he does not have to make the entries once again?

I would also like to indicate the errors made by highlighting the texboxes with the errors with a red color


There is no "magical" solution : when the form has been submitted with an error, you have to :

  • redisplay the form,
  • filling out the fields with what the used did input (what you received in $_GET or $_POST), putting those data in the right attributes
    • i.e. value for <input>
    • or as content for <textarea>
    • or setting the selected attribute for <select>
  • and, not forgetting to escape the data, with htmlspecialchars, to prevent HTML injections


For the indication of errors made, a solution is to add a CSS class to the form elements on which you have detected an error.

Adding something like class="error" for <input>s on which there's been an error, and having the .error class properly defined in your CSS file.


Generally the idea is to use:

<input type="text" name="field_1" id="field_1" class="<?= ($errors['field_1'] ? 'error':'') ?>" value="<?= @$_POST['field_1'] ?>" />

This fills the value of the text box with whatever the user inputed and gives you something to style if your script to handle this form deems this value to be invalid.

e.g.

if(empty($_POST['field_1']))
   $errors['field_1'] = 'Cannot be blank';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜