Test Password with Regex - javascript

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();
});

Related

Regex for contact number that does/doesn't start with a +

I have tried to create a basic South African contact number regex. Its not working though. The rules are simple.
10 digits or
11 digits if it starts with a +
Examples:
0119879874
0731231234
+27731231234
+27123456789
It must match only digits and length.
My attempt: [+\d]\d{9}\d{0,2}
I tested on the site https://regex101.com/ and it looked like it worked but not when i test it with /[+\d]\d{9}\d{0,2}/.test('12345gjhf6789123456')) then i get a true value.
You should specify ^ - begin of the string and end $
and
/^(\+\d)?\d{10}$/.test('12345gjhf6789123456'))
Rather than use a regex that will not provide any error messaging and is difficult to read (and maintain), I would suggest a simple validation function that lays out the rules explicitly:
function validate(num) {
if (num[0] === '+') {
return num.length === 11;
} else {
return num.length === 10;
}
}
This has a few advantages, including:
faster than a regex
easier to comment and expand later
can be replaced with a full blown predicate library or just an array of rules

Javascript RegExp test

I am trying to verify a pattern of 5 characters - 5 characters - 5 characters with Javascript and I want it to fail if there are more or less than 5 characters between dashes. My test is as follows:
var patterns = new RegExp("[2-46-9A-DF-HJKMP-RTVW-YX]{5}-[2-46-9A-DF-HJKMP-RTVW-YX]{5}-[2-46-9A-DF-HJKMP-RTVW-YX]{5}","gi");
if(patterns.test(fkLicense) == true) {
alert('good');
} else {
alert('bad');
}
My issue is, no matter what I set the value of fkLicense to, the test fails. Any help will be greatly appreciated.
I'm not sure what you're trying to match, but the problem is that you need to anchor your regular expression and it's alot easier to use a regular expression literal here instead ...
var patterns = /^ .... $/i
eval.in

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) {
...
}

HTML5 Pattern Regex Password Match

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?

Regex to validate a password [duplicate]

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.

Categories

Resources