I have the following regex which does not allow certain special characters:
if (testString.match(/[`~,.<>;':"\/\[\]\|{}()-=_+]/)){
alert("password not valid");
}
else
{
alert("password valid");
}
This is working. This regex will accept a password if it does not contain any of the special characters inside the bracket (~,.<>;':"\/\[\]\|{}()-=_+).
My problem here is it also don't allow me to input numbers which is weird.
Anything I missed here? Thanks in advance!
Here is a sample:
jsFiddle
You've got a character range in there: )-= which includes all ASCII characters between ) and = (including numbers). Move the - to the end of the class or escape it:
/[`~,.<>;':"\/\[\]\|{}()=_+-]/
Also, you don't need to escape all of those characters:
/[`~,.<>;':"/[\]|{}()=_+-]/
Note that in your case, it is probably enough for you, to use test instead of match:
if (/[`~,.<>;':"/[\]|{}()=_+-]/.test(testString))){
...
test returns a boolean (which is all you need), while match returns an array with all capturing groups (which you are discarding anyway).
Note that, as Daren Thomas points out in a comment, you should rather decide which characters you want to allow. Because the current approach doesn't take care of all sorts of weird Unicode characters, while complaining about some fairly standard ones like _. To create a whitelist, you can simply invert both the character class and the condition:
if (!/[^a-zA-Z0-9]/.test(testString)) {
...
And include all the characters you do want to allow.
Related
I am a newbie to regex and would like to create a regular expression to check usernames. These are the conditions:
username must have between 4 and 20 characters
username must not contain anything but letters a-z, digits 0-9 and special characters -._
the special characters -._ must not be used successively in order to avoid confusion
the username must not contain whitespaces
Examples
any.user.13 => valid
any..user13 => invalid (two dots successively)
anyuser => valid
any => invalid (too short)
anyuserthathasasupersuperlonglongname => invalid (too many characters)
any username => invalid because of the whitespace
I've tried to create my own regex and only got to the point where I specify the allowed characters:
[a-z0-9.-_]{4,20}
Unfortunately, it still matches a string if there's a whitespace in between and it's possible to have two special chars .-_ successively:
If anybody would be able to provide me with help on this issue, I would be extremely grateful. Please keep in mind that I'm a newbie on regex and still learning it. Therefore, an explanation of your regex would be great.
Thanks in advance :)
Sometimes writing a regular expression can be almost as challenging as finding a user name. But here you were quite close to make it work. I can point out three reasons why your attempt fails.
First of all, we need to match all of the input string, not just a part of it, because we don't want to ignore things like white spaces and other characters that appear in the input. For that, one will typically use the anchors ^ (match start) and $ (match end) respectively.
Another point is that we need to prevent two special characters to appear next to each other. This is best done with a negative lookahead.
Finally, I can see that the tool you are using to test your regex is adding the flags gmi, which is not what we want. Particularly, the i flag says that the regex should be case insensitive, so it should match capital letters like small ones. Remove that flag.
The final regex looks like this:
/^([a-z0-9]|[-._](?![-._])){4,20}$/
There is nothing really cryptic here, except maybe for the group [-._](?![-._]) which means any of -._ not followed by any of -._.
Im working on a password validation that should only allow a-z 0-9 and these characters "!"#$%&'()*+,-./:;<=>?#[\]^_{|}~`
I tried using a regex but I'm not too good with them and I wasnt sure if this is even possible or if Im not escaping the correct characters.
var allowedCharacters = /^[A-Za-Z0-9!"#$%&'()*+,-.\/:;<=>?#[\\]^_`{|}~]+$/;
if (!s.value.match(allowedCharacters)){
displayIllegalTextError();
return false;
}
You need to place the dash at the start or end of the regex, or it will try to create a character range (,-.). Then, a-Z isn't a valid range, you probably meant a-z. Also, you need to escape the closing brackets:
/^[A-Za-z0-9!"#$%&'()*+,.\/:;<=>?#[\\\]^_`{|}~-]+$/
Looking over the ascii chart here I see your regex could be reduced to this character range:
/^[\x21-\x7e]+$/
If you just want to learn special behavior of character classes, you should read up
on it via regex basic tutorials.
Note that class behavior differs amongst the different flavors.
Simpler and more to the point using unicode: ^[\u0021-\u007E]+$.
/^[\u0021-\u007E]+$/.test('MyPassword!') // returns true
/^[\u0021-\u007E]+$/.test('MyPassword™') // returns false
Now if you would like to go a few steps further and actually create a more complex validation such as: minimum length 8 characters and at least one lowercase, one uppercase, one digit and one special character:
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])[\u0021-\u007E]{8,}$
I am working on this code and using "match" function to detect strength of password. how can I detect if string has special characters in it?
if(password.match(/[a-z]+/)) score++;
if(password.match(/[A-Z]+/)) score++;
if(password.match(/[0-9]+/)) score++;
If you mean !##$% and ë as special character you can use:
/[^a-zA-Z ]+/
The ^ means if it is not something like a-z or A-Z or a space.
And if you mean only things like !#$&$ use:
/\W+/
\w matches word characters, \W matching not word characters.
You'll have to whitelist them individually, like so:
if(password.match(/[`~!##\$%\^&\*\(\)\-=_+\\\[\]{}/\?,\.\<\> ...
and so on. Note that you'll have to escape regex control characters with a \.
While less elegant than /[^A-Za-z0-9]+/, this will avoid internationalization issues (e.g., will not automatically whitelist Far Eastern Language characters such as Chinese or Japanese).
you can always negate the character class:
if(password.match(/[^a-z\d]+/i)) {
// password contains characters that are *not*
// a-z, A-Z or 0-9
}
However, I'd suggest using a ready-made script. With the code above, you could just type a bunch of spaces, and get a better score.
Just do what you did above, but create a group for !##$%^&*() etc. Just be sure to escape characters that have meaning in regex, like ^ and ( etc....
EDIT -- I just found this which lists characters that have meaning in regex.
if(password.match(/[^\w\s]/)) score++;
This will match anything that is not alphanumeric or blank space. If whitespaces should match too, just use /[^\w]/.
As it look from your regex, you are calling everything except for alphanumeric a special character. If that is the case, simply do.
if(password.match(/[\W]/)) {
// Contains special character.
}
Anyhow how why don't you combine those three regex into one.
if(password.match(/[\w]+/gi)) {
// Do your stuff.
}
/[^a-zA-Z0-9 ]+/
This will accept only special characters and will not accept a to z & A to Z 0 to 9 digits
i tried to make a regex for my Address column the code is:
var str = "97sadf []#-.'";
var regx = /^[a-zA-z0-9\x|]|[|-|'|.]*$/;
if(str.match(regx))
document.write('Correct!');
else
document.write('Incorrect!');
the special character i want that is ][#-. the given code return me the correct match but if i add another kind of the special character like #% then the correct result i got, but i want the incorrect result.
i don't know where i did wrong please help me to make right..
EDIT: Sorry guys but the one thing i have to discuss with you that is there is no necessary to enter the special characters that i mentioned ][#-., but if the someone enter other then the given special character then should return the incorrect.
The correct regex (assuming you want uppercase letters, lowercase letters, numbers, spaces and special characters [].-#') is:
var regx = /^[a-zA-Z0-9\s\[\]\.\-#']*$/
There are a couple things breaking your code.
First, [, ], - and . have special meaning, and must be escaped (prefixed with \).
\x checks for line breaks, where we want spaces (\s).
Next, lets look at the structure; for simplicity's sake, lets simplify to ^[abc]|[def]*$. (abc and def being your two blocks of character types). Since the * is attached to the second block, it is saying one instance of [abc] or any number of [def].
Finally, we don't need | inside of brackets, becuase they already mean one character contained within them (already behaves like an or).
I need help with a RegEx for a password. The password must contain at least one special char (like "§$&/!) AND a number.
E.g. a password like "EdfA433&" must be valid whereas "aASEas§ö" not as it contains not a number.
I have the following RegEx so far:
^(?=.*[0-9])(?=.*[a-zA-Z]).{3,}$
But this one is obviously checking only for a number. Can anyone help?
You're better off just using multiple more simple regular expressions: any code checking anything like this won't be performance sensitive, and the additional complexity of maintenance given a more complex regexp probably isn't justifiable.
So, what I'd go for:
var valid = foo.match(/[0-9]/) && foo.match(/["§$&/!]/);
I wonder if you really want to define special characters like that: Does é count as a special character? Does ~ count as a special character?
^(?=.*\d)(?=.*\W).{3,}$
checks for at least one digit (\d) and one non-alphanumeric character (\W). \W is the inverse of \w which matches digits, letters and the underscore.
If you want to include the underscore in the list of "special characters", use
^(?=.*\d)(?=.*[\W_]).{3,}$
I would divide function that checks if password is "hard" into some parts and in each part I would check one condition. You can see some complicated regex on Daily WTF with password reset: http://thedailywtf.com/Articles/The-Password-Reset-Facade.aspx