Yii 2.0: Simple revealing and hiding the password in the password field

4 followers

The problem with masked passwords

There are numerous usability problems:

  • Not being able to see what characters have been typed,
  • Not being able to check the input,
  • Not being able to correct an error.

For all this user inconvenience there are practically no security benefits at all:

  • How often is someone looking over your shoulder when you type a password?
  • The input isn't secured in any way, it's just a visual representation.
  • Password masking doesn't help prevent attacks from key loggers or malware.

This problem is well presented at http://passwordmasking.com.

Revealing the password

For better user experience we can add option to reveal typed password.

  • Password is masked at the beginning so no trust issues with the website security,
  • Revealing the password is optional so it depends on voluntary user action,
  • Password can be masked again.

The code

You can find example of form with password field in Basic Project Template available at https://github.com/yiisoft/yii2-app-basic/blob/master/views/site/login.php

Let's add additional checkbox under the password field.

<?= $form->field($model, 'password')->passwordInput() ?>
<?= Html::checkbox('reveal-password', false, ['id' => 'reveal-password']) ?> <?= Html::label('Show password', 'reveal-password') ?>

Now for a bit of JavaScript. The id of password field in the example is loginform-password but you can change it by adding ['id' => 'my-password-field-id'] array in passwordInput() method.

Add this in the view file:

<?php
$this->registerJs("jQuery('#reveal-password').change(function(){jQuery('#loginform-password').attr('type',this.checked?'text':'password');})");
?>

Now, every time "Show password" is checked text inside the password field is unmasked. Unchecking the box makes the text masked again.

Read more:

Total 2 comments

#19570 report it
Bizley at 2015/09/11 02:20am
Re: Label

The current way DOES allow that option. Your way is just more compact.

#19569 report it
skworden at 2015/09/10 05:05pm
Label

You should set the label in the checkbox html options that way a user can click the checkbox or the label to check the show / hide password box. The current way doesn't allow for that option.

<?= Html::checkbox('reveal-password', false, ['id' => 'reveal-password']) ?> <?= Html::label('Show password', 'reveal-password') ?>
 
should be 
 
Html::checkbox('reveal-password', false, ['id' => 'reveal-password', 'label' => 'Show Password']);

Leave a comment

Please to leave your comment.

Write new article