Passa al contingut principal

Tutorial: Create a Beautiful Password Strength Meter

Tutorial: Create a Beautiful Password Strength Meter:
In this tutorial we will be creating a beautiful password strength indicator. It will determine the complexity of a password and move a meter accordingly with the help of the new Complexify jQuery plugin. Only when a sufficiently complex password is entered, will the user be able to continue with their registration.
A PSD file is also available, so you can customize the form to your liking.

The HTML

We start off with a standard HTML5 document that will include our registration form. The form will only serve as an example of the password meter – if you need support for actual registrations, you will need to write the required server-side code.

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>How to Make a Beautiful Password Strength Indicator</title>

        <!-- The stylesheet -->
        <link rel="stylesheet" href="assets/css/styles.css" />

        <!--[if lt IE 9]>
          <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
    </head>

    <body>

        <div id="main">

         <h1>Sign up, it's FREE!</h1>

         <form class="" method="post" action="">

          <div class="row email">
        <input type="text" id="email" name="email" placeholder="Email" />
          </div>

          <div class="row pass">
           <input type="password" id="password1" name="password1" placeholder="Password" />
          </div>

          <div class="row pass">
           <input type="password" id="password2" name="password2" placeholder="Password (repeat)" disabled="true" />
          </div>

          <!-- The rotating arrow -->
          <div class="arrowCap"></div>
          <div class="arrow"></div>

          <p class="meterText">Password Meter</p>

          <input type="submit" value="Register" />

         </form>
        </div>

        <!-- JavaScript includes - jQuery, the complexify plugin and our own script.js -->
  <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
  <script src="assets/js/jquery.complexify.js"></script>
  <script src="assets/js/script.js"></script>

    </body>
</html>
We are including the latest version of jQuery, the Complexify plugin and our script.js right before the closing body tag for better performance.
Password Strength Meter
Password Strength Meter

jQuery

The jQuery code below is quite straightforward. We are binding a number of events to the form elements and validating them. If an error was encountered, we add an “error” class to the .row div that contains the input. This will display the red cross. The “success” class on the other hand will display a green check mark. When the form is submitted, we check whether all of the rows are marked as successful for allowing the submission.

assets/js/script.js

$(function(){

 // Form items
 var pass1 = $('#password1'),
  pass2 = $('#password2'),
  email = $('#email'),
  form = $('#main form'),
  arrow = $('#main .arrow');

 // Empty the fields on load
 $('#main .row input').val('');

 // Handle form submissions
 form.on('submit',function(e){

  // Is everything entered correctly?
  if($('#main .row.success').length == $('#main .row').length){

   // Yes!
   alert("Thank you for trying out this demo!");
   e.preventDefault(); // Remove this to allow actual submission

  }
  else{

   // No. Prevent form submission
   e.preventDefault();

  }
 });

 // Validate the email field
 email.on('blur',function(){

  // Very simple email validation
  if (!/^\S+@\S+\.\S+$/.test(email.val())){
   email.parent().addClass('error').removeClass('success');
  }
  else{
   email.parent().removeClass('error').addClass('success');
  }

 });

 /* The Complexify code will go here */

 // Validate the second password field
 pass2.on('keydown input',function(){

  // Make sure it equals the first
  if(pass2.val() == pass1.val()){

   pass2.parent()
     .removeClass('error')
     .addClass('success');
  }
  else{
   pass2.parent()
     .removeClass('success')
     .addClass('error');
  }
 });

});
With this out of the way, we can move on with the Complexify plugin that will validate the password. The plugin takes a callback function with two arguments – a percentage value from 0 to 100 depending on the complexity of the password, and a valid flag that takes into account the minimum length requirement, defined by the minimumChars property.
By tweaking the strengthScaleFactor property you can allow simpler passwords to be used. The default scale is 1 which requires a mix of upper and lower case letters, numbers and special characters, but I found it too strict so I lowered it to 0.7. You can lower it further if you need even simpler passwords.
pass1.complexify({minimumChars:6, strengthScaleFactor:0.7}, function(valid, complexity){

 if(valid){
  pass2.removeAttr('disabled');

  pass1.parent()
    .removeClass('error')
    .addClass('success');
 }
 else{
  pass2.attr('disabled','true');

  pass1.parent()
    .removeClass('success')
    .addClass('error');
 }

 var calculated = (complexity/100)*268 - 134;
 var prop = 'rotate('+(calculated)+'deg)';

 // Rotate the arrow. Additional rules for different browser engines.
 arrow.css({
  '-moz-transform':prop,
  '-webkit-transform':prop,
  '-o-transform':prop,
  '-ms-transform':prop,
  'transform':prop
 });
});
If a valid value has been passed, we will enable the second password field (it is disabled by default). We will also use CSS3 transformations to rotate the arrow. The transformation will be animated thanks to a transition property which you can see in the CSS section. The arrow moves from -134 to 134 degrees (the default 0 degrees correspond to the arrow pointing vertically up), so the code compensates for that.

CSS

I will include only the more interesting parts of the stylesheet here. The code that follows styles the arrow and defines a transition.

assets/css/styles.css

#main form .arrow{
    background: url("../img/arrow.png") no-repeat -10px 0;
    height: 120px;
    left: 214px;
    position: absolute;
    top: 392px;
    width: 11px;

    /* Defining a smooth CSS3 animation for turning the arrow */

    -moz-transition:0.3s;
    -webkit-transition:0.3s;
    -o-transition:0.3s;
    -ms-transition:0.3s;
    transition:0.3s;

    /* Putting the arrow in its initial position */

 -moz-transform: rotate(-134deg);
 -webkit-transform: rotate(-134deg);
 -o-transform: rotate(-134deg);
 -ms-transform: rotate(-134deg);
 transform: rotate(-134deg);
}

/* The small piece that goes over the arrow */
#main form .arrowCap{
 background: url("../img/arrow.png") no-repeat -43px 0;
 height: 20px;
 left: 208px;
 position: absolute;
 top: 443px;
 width: 20px;
 z-index: 10;
}
You can find the rest of the code in assets/css/styles.css. The best way to learn how it all works is by inspecting the working demo with Firebug or Chrome’s Developer tools and playing with the styles.

We’re done!

You can build upon this example and use it to present an eye catching validation option for your customers. And it is even easier to customize with the included PSD.

Comentaris

Entrades populars d'aquest blog

Learn Composition from the Photography of Henri Cartier-Bresson

“Do you see it?” This question is a photographic mantra. Myron Barnstone , my mentor, repeats this question every day with the hopes that we do “see it.” This obvious question reminds me that even though I have seen Cartier-Bresson’s prints and read his books, there are major parts of his work which remain hidden from public view. Beneath the surface of perfectly timed snap shots is a design sensibility that is rarely challenged by contemporary photographers. Henri Cartier-Bresson. © Martine Franck Words To Know 1:1.5 Ratio: The 35mm negative measures 36mm x 24mm. Mathematically it can be reduced to a 3:2 ratio. Reduced even further it will be referred to as the 1:1.5 Ratio or the 1.5 Rectangle. Eyes: The frame of an image is created by two vertical lines and two horizontal lines. The intersection of these lines is called an eye. The four corners of a negative can be called the “eyes.” This is extremely important because the diagonals connecting these lines will form the breakdown ...

El meu editor de codi preferit el 2024, que això ja se sap que va canviant 😄

Visual Code Visual Code és un editor de codi font lleuger, però potent que s’executa al teu escriptori i està disponible per a Windows, macOS i Linux. Compta amb suport integrat per a JavaScript, TypeScript i Node.js i té un ric ecosistema d’extensions per a altres llenguatges i entorns d’execució (com C++, C#, Java, Python, PHP, Go, .NET).  És una eina ideal per a desenvolupar i depurar aplicacions web i en el núvol. Per què Visual Code? Visual Code té molts avantatges com a editor de codi font, com per exemple: És gratuït, ràpid i fàcil d’instal·lar i actualitzar. Té un ampli ecosistema d’extensions que et permeten afegir funcionalitats i personalitzar la teva experiència de desenvolupament. Té un suport integrat per a molts llenguatges i entorns d’execució, i et permet depurar i executar el teu codi des del mateix editor. Té una interfície senzilla i elegant, amb diferents temes i modes de visualització. Té un sistema de sincronització de configuracions que et permet guardar les...

Las Mejores Aplicaciones Gratis para iPad de 2012

Las Mejores Aplicaciones Gratis para iPad de 2012 : ¿No tienes ni un duro? No te preocupes, pues hoy os traemos una extensa selección de las mejores apps gratuitas que puedes conseguir en la App Store para que llenes tu iPad de calidad, sin gastar nada de nada.   ¿Estás buscando juegos o apps gratis para tu iPad? En la App Store hay más de 500,000 apps y juegos, y una gran cantidad de ellos está disponible de forma totalmente gratuita. Aquí vamos con la selección de las mejores Apps gratis para iPad (todos los modelos), organizada por categoría. ¿Estás preparado? Las Mejores Apps Gratis de Redes Sociales para iPad Nombre Facebook Gratis Categoría Redes sociales Facebook es la red social más famosa del mundo , con casi mil millones de usuarios. Su app para iPad ha tardado, pero aquí está. Nombre Twitter Gratis Categoría Redes sociales Twitter es la red de microblogging por excelencia. La forma más rápida y directa de informar y mantenerse informado de las cosa...