summaryrefslogtreecommitdiff
path: root/static/js/password_strength.js
blob: af0b1c41b4fccf9fcf507bf4fd4045b0173af700 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
(function(){

function count(val, rxp){
  const match = val.match(rxp)
  return match ? match.length : 0
}

function passwordStrength(password, options={}) {
  const opt = Object.assign(options,{
    "minLength": 10,
    "minOther": 3,
    "texts" : [
        'Too weak',
        'Weak password',
        'Normal strength',
        'Strong password',
        'Very strong password'
    ]
  })

  
  const len = password.length
  if (len < opt["minLength"]) {
    return opt["texts"][0];
  }

  const num = count(password, /\d/g),
    lower = count(password, /[a-z]/g),
    upper = count(password, /[A-Z]/g),
    special = len - num - lower - upper,
    other = num + special

  if (lower == 0 || upper == 0 || other < opt["minOther"]) {
    return opt["texts"][0];
  }

  // Strength is just based on password length
  if (len < 11) {
    return opt["texts"][1];
  }else if (len < 13) {
    return opt["texts"][2];
  }else if (len < 16) {
    return opt["texts"][3];
  }else if (len >= 16) {
    return opt["texts"][4];
  }
 
  // falltrough
  return opt["texts"][1];
}


// auto setup for data-password-strength

document.querySelectorAll("input[data-password-strength]").forEach( ($elm) => {
  $elm.addEventListener("keyup", (e) => {
    const val = $elm.value;
    if (val.length > 0) {
      // check if we have a .password_strength beside the field
      let $info = $elm.parentNode.querySelector(".password_strength")
      if (!$info) {
        $info = document.createElement("span");
        $info.classList.add("password_strength");
        $elm.parentNode.appendChild($info);
      }
      $info.textContent = passwordStrength(val);
    }
  }, false)
})


document.querySelectorAll("input[data-same-as]").forEach( ($elm) => {
  const $target = document.querySelector("#"+$elm.dataset.sameAs)
  if ($target) {
    $elm.addEventListener("keyup", (e) => {
      if ($elm.value != $target.value) {
        $elm.setCustomValidity("Passwords do not match")
      }else{
        $elm.setCustomValidity("");
      }
    })
  }
});

})();