Why is my Javascript RegEx quantifier "not working"? - javascript

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

Related

use replace to remove chars not existing in a regex match

I'am trying to allow following pattern for a single html input box with javascript regex
-int (aka any minus number so long it not followed by a zero and is in the first position)
0 (a single zero is allowed)
int (is allowed)
I use this function the remove anything that doesn't match it
$('.dointcheck').live('keyup',
function () {
$(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
if ($(this).val().length == 0) {
$(this).val(0);
}
});
which doesn't work.
Other examples is:
/[^-0-9]/g it removes any non valid chars but doesnt check if the minus is the beginning and is followed by a zero. It allows minus everywhere in the string
(/^((?!:([1-9-]?[0-9])).)/g Don't allow none.
[^1-9-]?[^0-9]* Allow all...
I think I'am missing something.. Any suggestions would be most appreciated..
You may try this regex
^(0).*|^(-?)([1-9]\d*)?.*|^.*
and replace it with $1$2$3 after input
document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]\d*)?.*|^.*/g, '$1$2$3'));
<input />
It has three tests:
^(0).* // if it starts with 0, discard everything after it
^(-)?([1-9]\d*)?.* // otherwise it can only starts with a -, or any number that is not a 0. Then followed by other digits, then discard everything after it
^.* // if previous rules are not matched, discard everything
In short:
generally only -, 0-9 are allowed.
if you type a 0 first, nothing will be allowed after.
if you type a 1-9 first, only numbers are allowed after.
if you type a - first, only 1-9 is allowed next, then any digit is allowed after.
I changed your regexp and made it a bit more modular and it worked fine.
function toValidNumber(int) {
return (/^\s*[+-]?(\d+|\d*\.\d+|\d+\.\d*)([Ee][+-]?\d+)?\s*$/).test(int) ? int : 0;
}
$('.dointcheck').live('keyup',
function () {
$(this).val(toValidNumber($(this).val()));
});
Orginal RegEXP in Stackoverflow

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)

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

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?

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