Regex to validate a password [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Password validation regex
between 8 and 16 characters, with at least 1 character from each of the 3 character classes -alphabetic upper and lower case, numeric, symbols.
I have this code, but it doesn't work, when I write more than 16 characters, gives it as valid, but it should not; the it should to work ok with 3 character classes, but it works with 4, where's my mistake??
http://jsbin.com/ugesow/1/edit
<label for="pass">Enter Pass: </label>
<input type="text" id="pass" onkeyup="validate()">
Script
function validate() {
valor = document.getElementById('pass').value;
if (!(/(?=.{8,16})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*/.test(valor))) {
document.getElementById('pass').style.backgroundColor = "red";
} else {
document.getElementById('pass').style.backgroundColor = "#adff2f";
}
}

Regular expressions are not a panacea. It's not too hard to do it, mixing with regular code:
function validatePassword(password) {
// First, check the length.
// Please see my comment on the question about maximum password lengths.
if(password.length < 8 || password.length > 16) return false;
// Next, check for alphabetic characters.
if(!/[A-Z]/i.match(password)) return false;
// Next, check for numbers.
if(!/\d/.match(password)) return false;
// Next, check for anything besides those.
if(!/[^A-Z\d]/i.match(password)) return false;
// If we're here, it's valid.
return true;
}
However, I'd look into something like zxcvbn, a password checker, which I think is a better password quality checker, checking things like common dictionary words after un-13375p3/-\kification and dealing with entropy decently. It is used, among others, by Dropbox. Try it here.

You need to anchor the match to the beginning of the string, and anchor the first lookahead to the end:
^(?=.{8,16}$)
Also, the last lookahead needs to be split in two:
(?=.*?[A-Z])(?=.*?[a-z])

Why don't you just test for the three character sets with regular expressions:
[A-Za-z0-9]+
Then count the length of the string to validate the length.

What about this range:
/[A-Za-z0-9$-/:-?{-~!"^_`\[\]]/
So you can check first
/[A-Za-z]+/
then
/\d+/
and finally
/[$-/:-?{-~!"^_`\[\]]+/
If it passes you can check the length.
You can see this link to see why the symbols work.

Related

how can I fix password validation conditions with correct regex?

I am trying to fix my logical conditions that aren't working as intended.
For instance, the "2 digits in a password" condition fails on 1test2 even though it has 2 digits in it.
My rules are:
password must have at least 2 digits
password must have at least 6 letters
password must have at least 1 special character
password must be at least 8 characters long
https://codepen.io/skybulk/pen/OJNMPYO
function checkPassword(pwd){
const special_characters = "[~\!##\$%\^&\*\(\)_\+{}\":;,'\[\]]"
if(/[0-9]{2,}/.test(pwd)){ // at least 2 digits
return true;
}
if(/[a-zA-Z]{6,}/.test(pwd)){ // at least 6 letters
return true;
}
if(new RegExp(special_characters).test(pwd)){ // at leas 1 special character
return true;
}
if(pwd.length < 8){
return true;
}
}
I have not made any changes to your Regexp - only to the logic surrounding it. You might want to start with a variable valid and if any of these conditions are not met you can set valid = false. At the end of your function you want to return valid which will be a boolean of true or false depending on whether the password passed all tests.
function checkPassword(pwd){
let valid = true;
const special_characters = "[~\!##\$%\^&\*\(\)_\+{}\":;,'\[\]]"
if (!/[0-9]{2,}/.test(pwd)){ // at least 2 digits
valid = false;
}
if (!/[a-zA-Z]{6,}/.test(pwd)){ // at least 6 letters
valid = false;
}
if (!new RegExp(special_characters).test(pwd)){ // at least 1 special character
valid = false;
}
if (!pwd.length < 8){
valid = false;
}
return valid;
}
Side note: Complex password validation can be restrictive to the user. It is far more secure to encourage a user to have a longer password (or pass phrase) than a shorter password with a few special characters.
You may use
const regex = /^(?=.{8})(?=(?:\D*\d){2})(?=(?:[^a-zA-Z]*[a-zA-Z]){6})(?=[^~!##$%^&*()_+{}":;,'[\]]*[~!##$%^&*()_+{}":;,'[\]])/
See the regex demo (the pattern is a bit modified to avoid matching line breaks as the demo is performed against a single multiline string).
Details
^ - start of string
(?=(?:\D*\d){2}) - password must have at least 2 digits
(?=(?:[^a-zA-Z]*[a-zA-Z]){6}) - password must have at least 6 letters
(?=[^~!##$%^&*()_+{}":;,'[\]]*[~!##$%^&*()_+{}":;,'[\]]) - password must have at least 1 special character
(?=.{8}) - password must be at least 8 characters long.
You may write the regex with comments inside the code, too:
const regex = new RegExp("^" + // start of string
"(?=.{8})" + // must be at least 8 characters long
String.raw`(?=(?:\D*\d){2})` + // must have at least 2 digits
"(?=(?:[^a-zA-Z]*[a-zA-Z]){6})" + // must have at least 6 letters
String.raw`(?=[^~!##$%^&*()_+{}":;,'[\]]*[~!##$%^&*()_+{}":;,'[\]])` // must have at least 6 letters
);
console.log(regex);
Try with this. It seems easier to read and maintain:
function checkPassword(pwd){
const special_characters = /[%~!##$\^&*()_+{}":;,'\[\]]/;
return pwd.replace(/[^0-9]/g, '').length >= 2
&& pwd.replace(/[^a-zA-Z]/g, '').length >= 6
&& special_characters.test(pwd)
&& pwd.length >= 8
}
console.log(checkPassword('FF%lkf%jd%fk12'));
The idea is for every condition, remove all not-to-be-tested characters. Then you have the length of the characters that you are testing.
Bear in mind that in javascript, you can create a Regex object with the syntax:
some_variable = /foobar/;
You can create it via new Regex, however, in that case you are passing a string to the constructor. So if the regex was supposed to have a backslash, you should scape it too. Also, as regular strings, quotes should be scaped (one backslash).
This two are equivalent:
special_characters = /[%~!##$\^&*()_+{}":;,'\[\]]/;
special_characters = new Regex("/[%~!##$\\^&*()_+{}\":;,'\\[\\]]/");
Note that only ], ^, - must be scaped ([ is recommended and a must on other programming languages)
Also, when I read \! I was not sure if you tried to scape ! (which is unnecessary) or you tried to add backslash to the special character list (I opted for the first)

Not able to match the RegExp in JavaScript even it is matching in QuickRex

Not able to match the regular expression in my JavaScript code which I have written for form validation.
I wanted to validate my form field which is password using RegExp [[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]
My Validations on password is
- Should contain 10 characters including digit
- At least one uppercase letter should be there
- Only # should be used as special character
But the same is working with [0-9a-zA-Z#]{10} but not with [[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]
var regexpassword=/[[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]/
if(!regexpassword.test(password.value)){
alert("Enter valid password")
password.focus();
return false
}
NOTE: The password that I have entered is Welcome#67
It should not give the alert as "Enter valid password"
Best I can tell, the regex you provided, is matching exactly 1 character. the [] operator indicates "any of what is inside". But the only place you are indicating "multiple times" is the [A-Z]{1,8}. Also, as #Pointy mentioned, I don't think you can nest square brackets. Even if you can, it is somewhat redundant.
Your regex is being interpreted as follows:
1. Look for [ or the numbers 0 through 9 between 0 and 8 times in a row
2. Followed precisely by the lowercase letters a through z between 0 and 8 times in a row
3. Followed precisely by the uppercase letters A through Z between 1 and 8 times in a row
4. Followed precisely by a single #
5. Followed precisely by a single ]
This leads to matching strings like (but not limited to):
[A#]
0A#]
9aaaaaaaZ#]
[0123456abcdefghABCDEFGH#]
[[[[[[[[Q#]
[[[[[[[[azazazazAZAZAZAZ#]
but it will not match Welcome#67.
Is there a way to write a regex that will validate a password with your requirements?
Possibly.
Should you use a single regex to validate your password?
Probably not as the necessary complexity of that regex would make it impractical to maintain when your password requirements change.
Is there a practical, maintainable way to validate passwords?
Certainly! Use multiple regexes to validate the required parts of the password.
Then determine if the needed parts are present and make sure the length is acceptable.
Example:
var hasOnlyValidCharacters = /^[0-9a-zA-Z#]+$/gm.test(password.value);
var hasDigits = /[0-9]+/gm.test(password.value);
var hasUpper = /[A-Z]+/gm.test(password.value);
var hasLower = /[a-z]+/gm.test(password.value);
var hasAtSign = /[#]+/gm.test(password.value); // Technically could be /#+/gm.test(...), but I tend to use character classes every time I'm looking for specific characters.
var isValidPassword = (
password.value.length === 10 // Should contain 10 characters
&& hasOnlyValidCharacters
&& hasDigits // including digit
&& hasUpper // At least one uppercase letter should be there
// && hasLower // Uncomment to require at least one lowercase letter
// && hasAtSign // Uncomment to require at least one #
);
if (!isValidPassword) {
alert("Enter valid password")
password.focus();
return false
}
The [untested code] above should do the trick, and following the patterns established in it, you should be able to easily change your password requirements on a whim.

must at least have number and characters regex

I still don't understand how to use regex and there is regex like this :
/^[a-zA-Z0-9\s]+$/
and i use it in javascript
$('#oldPass, #newPass, #confpass').keydown(function (e) {
var inputValue = e.key;
if(inputValue.match(/^[a-zA-Z0-9\s]+$/)){
return;
}else{
e.preventDefault();
}
});
it works, i can't type anything beside alphanumeric, but how can i make that the new password must contain combination number and characters?
Minimum of 8 letters with atleast one letter and number.
^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}
check this link for verification
https://regex101.com/r/DcxNSc/1

What's wrong with my JavaScript regex / regex syntax?

I need a regex to use with javascript/jquery that fits these rules...
it will include 10 digits
if there is a leading 1 or +1 it should be ignored
valid characters allowed in the field are... 0-9,(), and -
I found a regex at Snipplr (the first one), but its not working. First of all, I'm not even sure if that regex fits my rules. Secondly, its allowing inputs like &^%$$#%^adfafsd. I believe the error is in my code not the regex. For example, are there supposed to be quotes around the expression?
Here is the code that is supposed to be validating the phone field...
$('#phone').bind('blur', function() {
var pattern = new RegExp("^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$");
if(pattern.test($('#phone').val())){
$("#phone").addClass("error");
return false;
}else{
$("#phone").removeClass("error");
return true;
}
return true;
})
When you're not using the literal form ( /[regex]/ ), you need to escape the regex string. Try this instead:
var regex = /^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$/;
if(regex.test($('#phone').val()){ ... }
if there is a leading 1 or +1 it should be ignored
it will include 10 digits
valid characters allowed in the field are... 0-9,(), and -
That could be matched with an expression like:
/^(?:\+?1)?[()-]*(?:\d[()-]*){10}$/

Test Password with Regex

I want to test a passwprd which must have at least 6 characters and 1 number in it. What regex string I can use with JS to get this done?
UPDATED
I forgot to write it must have at least 6 alpha characters and 1 numeric character but it should also allow special characters or any other character. Can you please modify your answers? I greatly appreciated your responses
This does smell a little like a homework question, but oh well. You can actually accomplish this concisely using a single regular expression and the "look ahead" feature.
/(?=.{6}).*\d.*/.test("helelo1")
The first bit in the brackets says "peek ahead to see if there's 6 characters". Following this we check for any number of characters, followed by a number, followed by any number of characters.
It is even possible to accomplish your goal in a single regex without having the faculty of look ahead... It's just a little hard to look at the solution and not wince:
new RegExp("[0-9].....|" +
".[0-9]....|" +
"..[0-9]...|" +
"...[0-9]..|" +
"....[0-9].|" +
".....[0-9]").test("password1")
Try this:
password.match(/(?=.*\d).{6}/);
More info here.
As far as I know this is best done with a combination of string functions and regex:
if( myPass.match(/[a-zA-Z]/).length >= 6 && myPass.match(/\d/g).length ) {
// Good passwords are good!
}
EDIT: Updated to include the new stipulations. Special characters are allowed, but not required.
if (/.{6,}/.test(password) && /\d/.test(password)) {
// success
} else {
// fail
}
/^(?=[\w\d]{6,}$)(?=.*\d)/.test(password)
requires 6 or more characters (letters, numbers or _)
requires at least one digit
won't allow any special characters
This is a js to check password,
it checks min 7 chars, contains 1 Upper case and 1 digit and 1 special character and must not contain a space, hope it will help you.
pwLength = this.value.length;
if (pwLength > 7 && pwLength < 21) {
charLengthIcon.removeClass("fail").addClass("pass");
}
else charLengthIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[A-Z]/g)) {
capLetterIcon.removeClass("fail").addClass("pass");
}
else capLetterIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[0-9]/g)) {
numberIcon.removeClass("fail").addClass("pass");
}
else numberIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[##$%!$&~*^(){}?><.,;:"'-+=|]/g)) {
splcharIcon.removeClass("fail").addClass("pass");
}
else splcharIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[\s/]/g)) {
whiteSpce.removeClass("pass").addClass("fail");
}
else whiteSpce.removeClass("fail").addClass("pass");
confirmPW();
});

Categories

Resources