HTML5 Pattern Regex Password Match - javascript

Looking for some help for validating password with the following rules:
8+ characters
contains at least 1 upper case letter
contains at least 1 lower case letter
contains at least 1 number
Cannot start with a number
contains no special characters
I had gotten as far as:
(?=.*\d.*)(?=.*[a-z].*)(?=.*[A-Z].*)(?=.*[!#\$%&\?].*).{8,}
but can't seem to figure out how to get the first digit to not match a digit, and set the special character class to not match as well. Any help would be greatly appreciated.

I find that breaking this down into individual tests is:
easier to code
easier to read
easier to maintain
and more flexible when requirements change
Try something like this:
var testPassword = function (password) {
var minLengthMet = password.length >= 8,
hasUpper = (/[A-Z]+/).test(password),
hasLower = (/[a-z]+/).test(password),
hasNumber = (/[0-9]+/).test(password),
letterBegin = (/^[A-Za-z]/).test(password),
noSpecials = !(/[^A-Za-z0-9]+/).test(password);
return minLengthMet && hasUpper && hasLower && hasNumber && letterBegin && noSpecials;
};
See it in action here: http://jsfiddle.net/H9twa/

Here is what I would go with:
(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*[!#\$%&\?])^\D.{7}
Note that the .* after each look-ahead term was superfluous.
(?!...) is a negative look-ahead, to make sure there are no special characters.
^\D requires that the first character be a non-digit. Then I simply require 7 characters after that, because the end is not enforced.
But why exclude special characters from passwords? Usually just the opposite is encouraged.

How about:
pwd.length >= 8 &&
pwd.match(/[A-Z]/) &&
pwd.match(/[a-z]/) &&
pwd.match(/\d/) &&
!pwd.match(/^\d/) &&
!pwd.match(/[!#\$%&\?]/);
Just in case you need to maintain this code ever?

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.

Why is my Javascript RegEx quantifier "not working"?

This question seems to have such an easy answer and an ashaming one for me, that I hope you just comment, then I can delete the thread after solving. ;)
I have a problem with the {n} quantifier in my RegEx. It does not seem to work!
Here my code
document.time.Id.onkeyup = function() {
var that = this.value,
regex = /^[1-9]{1}/
if (that) {
if (!that.match(regex)) {
this.nextSibling.innerHTML="Number must be between '1' and '100'.";
} else {
this.nextSibling.innerHTML="";
}
} else {
this.nextSibling.innerHTML="";
}
}
As you can see, I want to match against 1 till 100 in the end, but I am stuck at the bit, that the quantifier does not work. When I key in 0 there is a match failure, as well with any letter...so it does work "a bit".
Can you please help me?
Your regular expression says to match any string that starts (because it's anchored at the beginning using ^) with any digit between 1 and 9. This is why it doesn't match 0 or letters.
A range validation is something you'd want to check using basic number comparisons:
var numberValue = parseInt(this.value, 10);
if (numberValue >= 1 && numberValue <= 100) {
// valid number
}
For the sake of completeness, you could create a regular expression for that purpose which I don't recommend, though:
^(?:[1-9][0-9]?|100)$
Try using this regex instead:
^[1-9][0-9]?$|^100$
The quantifier you used is actually redundant, since [1-9] and [1-9]{1} mean the same thing.
If you input 1000 with your current code and regex, the number will pass because a match counts as long as the regex matches any part of the string. Using $ (end of line anchor) forces the regex to check the whole string.
But you should probably be using a simple if check for that.
if (that > 0 && that <= 100 && that % 1 == 0) {
...
}

Password RegEx - not working

I need a RegEx for a password that must contain:
at least one uppercase character
at least one lowercase character
at least one digit
at least one symbol character out of: `~!##$%^&*()_-+={}[]|:;"'<>,.?/ and the space character
should have a minimum length of 6 ch.
So far I came up with this:
^\S*(?=\S{6,})(?=.*[A-Z])(?=.*[a-z])(?=.*\d)([`\~\!##\$%\^&\*\(\)_\-\+={}\[\]\|:;"'<>,\.\?\/ ])\S*$
But for some reason it's not working as I hoped. I've always had trouble with these things, so any help would be much appreciated.
Thank you.
That's not very expressible as a single regexp. As you've tagged "javascript", here's how I'd do it in JS.
function validatePassword(password) {
return password.length >= 6 &&
/[A-Z]/.exec(password) &&
/[a-z]/.exec(password) &&
/[0-9]/.exec(password) &&
/[ `~!##$%^&*()_-+={}\[\]|:;"'<>,.?\/]/.exec(password);
}
This should work:
/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[`\~\!##\$%\^&\*\(\)_\-\+={}\[\]\|:;"'<>,\.\?\/ ]).{6,}/;
The full explanation how i did this is on art of web website

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