简体   繁体   中英

password validation script is not working

I am using following script to validate password. Aims For validations are :

  1. Password field should not be empty
  2. Password Length should be between 6 and 10 characters
  3. Password should not contain spaces and special characters
  4. Password should be Alphanumeric.

But With following code , it passes first 3 aims but even after entering Alphanumeric text, it is till alerting:

"Password Should Contain Alphabet And Numbers Both".

Need your help

Code is :

if(document.subForm.password.value==""){
  alert("Please Enter Your Desired Password....");
  document.subForm.password.focus();
  return false;
}
if(document.subForm.password.value.length < 6 || document.subForm.password.value.length > 10){
  alert("Password Length Should Be In Between 6 And 10 Characters.");
  document.subForm.password.focus();
  return false;
}
var re = /^[\w\A-Z]+$/;
if(!re.test(document.subForm.password.value)) {
  alert ("Your Password Has Spaces In Between The Words \n\nOr\n\nIt Contains Special Characters.\n\nThese Are Not Allowed.\n\nPlease Remove Them And Try Again.");
  document.subForm.password.focus();
  return false;
}
var realphanumeric = /^[a-z_A-Z_0-9]+$/;
if (!realphanumeric.test(document.subForm.password.value)){ 
  alert("Password Should Contain Alphabet And Numbers Both");
  document.subForm.password.focus();
  return false;
}

Aragon0 suggested to use an open-source script from dropbox to check password strength. I recommend checking it out.


If you'd like one regular expresion to check everything:

^\w{6,10}$

Explanation:

  1. From start ( ^ ) to end ( $ ) of the string...
  2. match only alphanumeric characters ( [A-Za-z_0-9] ),
  3. with a length of 6-10 characters ( {6-10} )

If you want to force the user to have at least one number you can do that like this:

^(?![A-Za-z_]+$)\w{6,10}$

Your regex

/^[a-z_A-Z_0-9]+$/

doesn't do what you want. It will match the password "Test" but not "te@st".

You could use two regexes, which both need to match:

/[a-zA-Z]+/
/[0-9]+/

Btw, you should not enforce alphanumeric passwords or length constraints. You could use Dropbox's password strength script ( https://github.com/dropbox/zxcvbn ) Some sample code with zxcvbn:

<script src="//cdn.jsdelivr.net/zxcvbn/1.0/zxcvbn-async.js" />
<script>
var result = zxcvbn(document.subForm.password.value);
if(result.entropy<56) // 56 is very secure, you could also lower it to 48 if you need to.
{
    alert("Your password is too weak. It would be cracked " + result.crack_time_display);
    return false;
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM