HTML.form.guide

HTML input type password field - example code and techniques

html input type password input type password

The HTML <input type=“password”> element is a specific type of input elements used to create input fields that deal with passwords . It is designed to deal with passwords so it’s more secure than the normal <input type=‘text’> we see in every form on the internet.

First: It makes the password not visible to anybody sitting around you by showing “.” or “*” instead of the characters you type.

Second: Browsers treat inputs with text type and password types differently, browsers may try to automatically refill the text input types if they have been previously entered which is something you may not always want.

HTML <input type=”password”> element is where you should make the user type their password in, and in this article, we will know how we can customize the password input fields to accommodate our needs.

By the end of this tutorial, you will know how to

  1. create a password input field and style it
  2. add a button that can enable the user to view his password in plain text
  3. add validation to your password input field
  4. create a numbers only password field

Creating a password input field is as simple as typing <input type=“password”> and it will come packed with everything we need as hiding the password and replacing it with dots.

Now it’s time to add some logic to our example here, we will create an eye icon that you can click to show the password and click again to hide it.

Show/Hide Password Mask


<div class="first-example">
  <input type="password" id="password-field" >
  <i id="pass-status" class="fa fa-eye" aria-hidden="true" onClick="viewPassword()"></i>
</div>

Here, all that I have done is created a div that contains the password input field and it has an id of “password-field” which we will use later to give it style and reference it in our javascript file next we created an I element with class “fa fa-eye” and id of “pass-status” which will create an eye icon using fontawesome

Note: if you are not familiar with font awesome do not worry it’s a simple font that contains many icons that are used all over the web as they are very easy to style.

We also added an onClick event to our icon that calls a function called viewPassword each time it is clicked. Here is the final result so far do not worry if yours looked different you can copy all the CSS from our codepen

Now we need to create the javascript code to check if the password is already hidden view it and change the icon to a crossed eye.

  var passwordInput = document.getElementById('password-field');
  var passStatus = document.getElementById('pass-status');

To make this example work we need to check first to see if the password is hidden and view it also change the icon to match the view state. To do all this we will use a small trick , we know that what makes our password hidden is the use of “password” as a type for our input so all that we have to do is when the icon is clicked we will check if our input had a type of “password” we will change it to type “text” which will lead to showing the password till the user click again on the icon.

  if (passwordInput.type == 'password')
  {
    passwordInput.type='text';
    passStatus.className='fa fa-eye-slash';
  }
  else
  {
    passwordInput.type='password';
    passStatus.className='fa fa-eye';
  }

Remember all this code is written inside the viewPassword() function. All that we are doing here is using an if statement to check if our password input’s type is “password” then change it to text and change the class of the icon’s class to “fa fa-eye” which is the class for a slashed eye in font awesome. If the input had already a text type which means the icon has already been clicked we will reverse everything we have done by changing the input type back to password and the icon class name to “fa fa-eye” which will make the password hidden again.

Checking for Password Strength

Enabling the user to show and hide his password is not all that we can do , a study has show that one each fiver users use 123456 as their password which is very unsafe and all the fancy stuff website developers do nowadays from hashing to salting all of this will not make any difference if the hacker can simply guess your password and if you use any in the list of top famous 25 password , there is a pretty good chance the hacker may be able to guess it right. One way we can solve this issue is to add validation to your password input. For example, force your user to create a password that contains at least one letter, one digit, and 8 characters. And this is exactly what we will do now.


  <div class="second-example">
    <input type="password" id="password-2" onkeyup="validate();">
  </div>
  <div id="validation-txt">
  </div> 

Here we did the same as the first example we created a div with a class of “second-example” and added in it a password input with an id of “password-2” and I added an onkeyup event and made it’s value equal to a validate() function .

Note : we used here onkeyup event because onkeydown will fire the event once the key is pressed before even the character is typed on the screen which will lead to a problem causing the password to not be written.

We also added a div with an id of “validation-txt” that will contain all the warning that we will display to the user.

Now we need to create the javascript that will make all this happen. First, we create the function validate() that will contain all our code

function validate()
{
  var  validationField = document.getElementById('validation-txt');
  var  password= document.getElementById('password-2');

  var content = password.value;
  var  errors = [];
}

In the code above we used document.getElementById to grab the password input and the validation div that will contain all our warnings . We also created a variable called content and we assigned it to password.value which is the value of out password input field, we also created an empty array that will contain all our validation errors to be able to view them to the user.

Next, we need to start validating the password each time a character is typed and check if it satisfies our validation conditions or not.

As I mentioned before we will check if the password’s length is greater than 8 characters and if it contains at least one letter and one digit.

We will start by the easiest one which is checking that the password is longer than 8 characters

  if (content.length < 8) 
  {
    errors.push("Your password must be at least 8 characters"); 
  }

Here, we are using the length property to check if our password has less than 8 characters and if it does we are using the push function to push the string “Your password must be at least 8 characters” to the errors array we created before.

Next we need to check if the password field contains at least one letter. Unfortunately, there is no native way we can do this easily in javascript so we will have to use regular expression or as sometimes called “regex”. Do not worry if you are not familiar with regular expressions or never heard of them before: regular expression is a special string that describes a search format, we can use it to search for a phone number in a long document by just knowing it’s format 998- 902-142. Here we are going to use it to check once if the password contains at least one letter and if it contains at least one digit.

  if (content.search(/[a-z]/i) < 0) 
  {
    errors.push("Your password must contain at least one letter.");
  }
  if (content.search(/[0-9]/i) < 0) 
  {
    errors.push("Your password must contain at least one digit."); 
  }
 

Here we are using the search function which is a special regular expression function built natively to javascript to check a regular expression term against a string. Here “/[a-z]/i” means that the search function will be searching for any character from a to z and “/[0-9]/i” will search for any digit between 0 and 9 and if it does not wound any it uses the push function we have talked about earlier in this tutorial to add the warning string to the errors array.

The last thing we need to do is to add the errors we collected in our errors array to out HTML.

if (errors.length > 0) 
{
  validationField.innerHTML = errors.join(',');
  return false;
}
  validationField.innerHTML = errors.join(',');
  return true;

Here we are using an if statement to check if the number of elements in the array is greater than zero which means there have been validation errors then we use the join function to attach all the elements of the array together in one string separated by the “,” comma sign then adding our results to the html in the validation div we have created.

“Digits only” Password field using CSS

The last thing we are going to learn about in this tutorial is how to make a password input field that accepts numbers only. This is very useful for example if you are trying to create an input field for a pass code that needs to be only in numbers and want the mobile users to automatically see the number pad once the click on the input field .

This time we will not be creating a password input field , we are going to be creating a numeric input field instead


<input type="number" id="password-3" pattern="[0-9]*" >

Here we created an input element with a type of number and added pattern="[0-9]*" this is supported in safari and most browsers and will make the number pad in the mobile phone pop up automatically once the input field is in focus.

What is remaining now is to hide the password to make it look like other password inputs that we have made and remove the number spinner that appears by default in a lot of browser. Fortunately, this is very easy using CSS 3.

#password-3{
  -webkit-text-security: disc;
    -moz-text-security:circle;
     text-security:circle;
}
input[type=number]::-webkit-inner-spin-button, 
input[type=number]::-webkit-outer-spin-button { 
  -webkit-appearance: none; 
  margin: 0; 
}  

In the first part, we are using the id of the input element to hide the password and replace it with the dots like other input field with type of password and the second part we are changing the style of every input element with type number to change the outer and inner spinners that sometimes appear natively in some browsers to enable users to increase and decrease numbers.