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,}$
Related
I have constructed the following Regex, which allows strings that only satisfy all three conditions:
Allows alphanumeric characters.
Allows special characters defined in the Regex.
String length must be min 8 and max 20 characters.
The Regex is:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]$"
I use the following Javascript code to verify input:
var regPassword = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]$");
regPassword.test(form.passwordField.value);
The test() method returns false for such inputs as abc123!ZXCBN. I have tried to locate the problem in the Regex without any success. What causes the Regex validation to fail?
I see two major problems. One is that inside a string "...", backslashes \ have a special meaning, independent of their special meaning inside a regex. In particular, \d ends up just becoming d — not what you want. The best fix for that is to use the /.../ notation instead of new RegExp("..."):
var regPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]$/;
The other problem is that your regex doesn't match your requirements.
Actually, the requirements that you've stated don't really make sense, but I'm guessing you want something like this:
Must contain at least one lowercase letter, at least one uppercase letter, at least one digit, and at least one of the special characters $#$!%*?&.
Can only contain lowercase letters, uppercase letters, digits, and the special characters $#$!%*?&.
Total length must be between 8 and 20 characters, inclusive.
If so, then you've managed #1 and #2, but forgot about #3. Right now your regex demands that the length be exactly 1. To fix this, you need to add {8,20} after the [A-Za-z\d$#$!%*?&] part:
var regPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]{8,20}$/;
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.
I was just looking for a regex expression to check and see if both numbers and letters exist.
Just to clarify the query, the regex is going to be written in javascript and used to validate an address.
I would use a regular expression which matches any letter followed by any digit (with any possible characters in between) or digit then letter (with anything in between):
var hasNumbersAndLetters = function(str) {
var regex = /(?:[A-Za-z].*?\d|\d.*?[A-Za-z])/;
return !!str.match(regex);
};
Much easier to run two checks.
/\pL/ && /\pN/
To do both checks in one pattern, you need something like
/\pL.*\pN|\pN.*\pL/s
Languages supporting zero-width lookaheads can eliminate the redundancy:
/^(?=.*\pL/)(?=.*\pN/)/s ( or /^(?=.*\pL/).*\pN/s )
But it's harder to read.
Pardon me for not using JS's match function, but the question is really about regular expressions, and I'm not familiar with JS's match function.
if it is a single word you are matching without spaces, with both numbers and letters, it can be assumed they touch somewhere - so if it matches letter then number or number then letter we have a match - so:
([a-zA-Z][0-9]|[0-9][a-zA-Z])
Edit: where there may be spaces then you can use lookahead assertions like this
([a-zA-Z](?=.*[0-9])|[0-9](?=.*[a-zA-Z]))
Saw you wanted to validate an address
Removed by regex answer as javascript has no Unicode support, except for matching single characters http://www.regular-expressions.info/unicode.html
This should do it:
^[\w]*[^\W_][\w]*$
I would like to construct a regular expression that matches any letter (including accented and Greek), number, hyphens and spaces with a total allowed characters length between 3 and 50.
This is what I made:
[- a-zA-Z0-9çæœáééíóúžàèìòùäëïöüÿâêîôûãñõåøαβγδεζηθικλμνξοπρστυφχψωÇÆŒÁÉÍÓÚŽÀÈÌÒÙÄËÏÖÜŸÂÊÎÔÛÃÑÕÅØΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ]{3,50}
Now I wan't to adjust the expression so that it can't start with a hyphen or space. It will be used to validate a username.
I thought about using a negative lookbehind but these are the limitations:
JavaScript doesn't support a lookbehind.
The alternatives for a lookbehind aren't really applicable since they all depend on other JavaScript functions and I am bound to using the match function.
I hope there are any regular expression heroes here since it doesn't look simple.
I replaced your long character class with a-z for readability:
[a-z][- a-z]{2,49}
You could also match with your current regex and then make sure that the string does not match ^[ -] in another match.
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