-2

It doesn't work properly, I get the Password doesn't match! for each password I write with letters, numbers and Uppercase Letters

var reg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$"/; 

var pass = document.getElementById("password").value;
if (pass == "") {
  alert("Enter the user password");
  document.getElementById("password").focus();
  return false;
}

if (pass.length < 8) {
  alert("Password too short, at least 8 characters");
  document.getElementById("password").focus();
  return false;
}
var pasw = pass.match(reg);
if (pasw) {
  alert("Password is valid");
} else {
  alert("Password doesn't match!");
  return false;
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Gresa
  • 1
  • Could you clarify your question and properly format your post? – Nico Haase Jan 13 '18 at 14:22
  • What is the output? Also use if(pass) instead of if(pass=="") as javascript coerces pass to a boolean value and if the pass is null, empty or undefined it won't enter the if loop. – loki Jan 13 '18 at 14:24
  • @loki pasw is a boolean value the problem is in the last part of the code with the match method I need to get Password is valid If I write a password containing Uppercase,Lowercase and number but instead I always get Password doesn't match! – Gresa Jan 13 '18 at 14:30
  • @NicoHaase I need to get Password is valid If I write a password containing Uppercase,Lowercase and number but instead I always get Password doesn't match! – Gresa Jan 13 '18 at 14:30
  • maybe you should verify your regex – loki Jan 13 '18 at 14:38
  • https://regex101.com/ – mplungjan Jan 13 '18 at 14:40
  • @loki thank you I wrote " after $ that was the problem. – Gresa Jan 13 '18 at 14:51

1 Answers1

0

First, Use var reg = ^(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}$ instead of var reg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$"/; base on this result :

Regular expression to enforce complex passwords, matching 3 out of 4 rules

Second, Use reg.test(pass) instead of pass.match(reg).

JavaScript test() Method

The test() method tests for a match in a string. This method returns true if it finds a match, otherwise it returns false.

var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);
Fred
  • 3,365
  • 4
  • 36
  • 57