Password/password confirm JavaScript form checker, triggered via getElementById().addEventListener()

A javascript function for validating two passwords, which optionally disables the submit button unless the passwords are equal. Source code, including an example-use html page, is below.

empty password
passwords do not match
passwords match

/**
   @private

   Nothing to see here. Move along. Private function needed by the main
   function, just below.
 **/
function _disableSubmitButtonIfIdNonNull(is_disabled, id_nullIfDontDisable)  {
   if(id_nullIfDontDisable == null)  {
      return;
   }
   try  {
      document.getElementById(id_nullIfDontDisable).disabled = is_disabled;
   }  catch(err)  {
      throw  "Attempting to get disable element id_nullIfDontDisable (\"" + id_nullIfDontDisable + "\"): " + err;
   }
}
/**
   @function

   For use on HTML forms containing two password fields, where both must
   match. Provides a green alert when equal, and a red alert when not.
   If either password contains no characters, no alert is given.
   Optionally disables the submit button unless passwords match.

   Derived from (downloaded 8/27/2014)
      http://keithscode.com/tutorials/javascript/3-a-simple-javascript-password-validator.html

   Jeff Epstein: Added the following:

      - all optional parameters
      - The "don't print any alert if one or both fields are empty" feature.
      - The optional "disable submit button feature"
      - Throwing more helpful messages when form elements do not exist.
      - This JSDoc

   With thanks to zkanda on #django irc, for the idea of moving event listeners out of form elements.

   @param  {string}  password1_id  "id" identifier (ID) of the
   first-password element.
   @param  {string}  password2_id  ID of the second-password element
   (the "confirm").
   @param  {string}  submit_buttonIdNullIfDontDisable  ID of the submit
   button that should be disabled, unless the passwords match. If
   `null`, the button is never disabled (or abled).
   @param  {string}  passwordsMatch_messageSpanId  ID of the span in
   which to display the "do not match!" message. If null, defaults to
   "passwords_match_message_span".
   @param  {string}  good_color  The hex color, including the initial
   hash ('#') to change both the password confirmation, and message-text
   to, when the passwords match. If `null`, defaults to `"#66cc66"`.
   @param  {string}  bad_color  The hex color when the passwords do not
   match. If `null`, defaults to `"#ff6666"`.

   @example
      <HTML><HEAD>
         <TITLE>Create account</TITLE>
         <script src="js/passwords_match_alert.js"></script>
      </HEAD><BODY>
         <h1>Create account</h1>

         <form id="user_form" method="post" action="/accounts/register/">

            <p>Username: <input id="id_username" maxlength="30" name="username" type="text" /></p>
            <p><label for="id_password1">Password:</label> <input id="id_password1" name="password1" type="password" /></p>
            <p><label for="id_password2">Password confirmation:</label> <input id="id_password2" name="password2" type="password" /></p>

            <!-- Where passwordsMatchAlert() writes its message -->
            <span id="passwords_match_message_span" class="passwords_match_message_span"></span>

            <P><input type="submit" id="id_submit_button" name="submit" value="Create account" /></P>
         </form>

      <script language="JavaScript">
         var idPass1 = "id_password1";  //id of password field 1
         var idPass2 = "id_password2";  //id of password field 2
         var idSubmit = "id_submit_button";  //id of the submit button
         function triggerCheckPass()  {
            //See documentation for additional optional parameters
            passwordsMatchAlert(idPass1, idPass2, idSubmit);
         }
         //"keyup" must be lowercase!
         document.getElementById(idPass1).addEventListener('keyup', triggerCheckPass);
         document.getElementById(idPass2).addEventListener('keyup', triggerCheckPass);
         document.getElementById("id_username").focus();
         document.getElementById(idSubmit).disabled = true;
      </script>
      </BODY></HTML>
 */
function passwordsMatchAlert(password1_id, password2_id, submit_buttonIdNullIfDontDisable, passwordsMatch_messageSpanId, good_color, bad_color)  {
   //Disable submit button by default.
   _disableSubmitButtonIfIdNonNull(true, submit_buttonIdNullIfDontDisable);

   if(passwordsMatch_messageSpanId == null)  {
      passwordsMatch_messageSpanId = "passwords_match_message_span";
   }


   var pass1 = null;    //Password field elements
   var pass2 = null;
   var message = null;  //Message Object span element
   try  {
      pass1 = document.getElementById(password1_id);
      pass2 = document.getElementById(password2_id);
      message = document.getElementById(passwordsMatch_messageSpanId);
   }  catch(err)  {
      throw  "Attempting to obtain elements by id: password1_id (\"" + password1_id + "\"), password2_id (\"" + password2_id + "\"), passwordsMatch_messageSpanId (\"" + passwordsMatch_messageSpanId + "\"): " + err
   }

   //Set the colors we will be using ...
   if(good_color == null)  {
      good_color = "#66cc66";
   }
   if(bad_color == null)  {
      bad_color = "#ff6666";
   }

   //Compare the values in the password field
   //and the confirmation field
   if(pass1.value.length === 0  ||  pass2.value.length === 0)  {
      //One or both passwords are empty
      pass2.style.backgroundColor = "#FFFFFF";
      message.style.color = "#FFFFFF";
      message.innerHTML = "";
      return;
   }

   if(pass1.value === pass2.value){
      //The passwords match.
      //Set the color to the good color and inform
      //the user that they have entered the correct password
      pass2.style.backgroundColor = good_color;
      message.style.color = good_color;
      message.innerHTML = "Passwords Match!"
      _disableSubmitButtonIfIdNonNull(false, submit_buttonIdNullIfDontDisable);

   }  else  {
      //The passwords do not match.
      //Set the color to the bad color and
      //notify the user.
      pass2.style.backgroundColor = bad_color;
      message.style.color = bad_color;
      message.innerHTML = "Passwords Do Not Match!"
   }
}
Advertisements

2 thoughts on “Password/password confirm JavaScript form checker, triggered via getElementById().addEventListener()

  1. Pingback: JavaScript form validation for file-uploads–enforcing the extension to be in an approved list. | aliteralmind — Computer Programming Blog

  2. Pingback: JavaScript form validation for file-uploads–enforcing the extension to be in an approved list. | aliteralmind — Computer Programming Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s