This question already has answers here:
Why is this regex allowing a caret?
(3 answers)
Closed 1 year ago.
I am using javascript regex to do some data validation and specify the characters that i want to accept (I want to accept any alphanumeric characters, spaces and the following !&,'\- and maybe a few more that I'll add later if needed). My code is:
var value = userInput;
var pattern = /[^A-z0-9 "!&,'\-]/;
if(patt.test(value) == true) then do something
It works fine and excludes the letters that I don't want the user to enter except the square bracket and the caret symbols. From all the javascript regex tutorials that i have read they are special characters - the brackets meaning any character between them and the caret in this instance meaning any character not in between the square brackets. I have searched here and on google for an explanation as to why these characters are also accepted but can't find an explanation.
So can anyone help, why does my input accept the square brackets and the caret?
The reason is that you are using A-z rather than A-Za-z. The ascii range between Z (0x5a) and a (0x61) includes the square brackets, the caret, backquote, and underscore.
Your regex is not in line with what you said:
I want to accept any alphanumeric characters, spaces and the following !&,'\- and maybe a few more that I'll add later if needed
If you want to accept only those characters, you need to remove the caret:
var pattern = /^[A-Za-z0-9 "!&,'\\-]+$/;
Notes:
A-z also includesthe characters: [\]^_`.
Use A-Za-z or use the i modifier to match only alphabets:
var pattern = /^[a-z0-9 "!&,'\\-]+$/i;
\- is only the character -, because the backslash will act as special character for escaping. Use \\ to allow a backslash.
^ and $ are anchors, used to match the beginning and end of the string. This ensures that the whole string is matched against the regex.
+ is used after the character class to match more than one character.
If you mean that you want to match characters other than the ones you accept and are using this to prevent the user from entering 'forbidden' characters, then the first note above describes your issue. Use A-Za-z instead of A-z (the second note is also relevant).
I'm not sure what you want but I don't think your current regexp does what you think it does:
It tries to find one character is not A-z0-9 "!&,'\- (^ means not).
Also, I'm not even sure what A-z matches. It's either a-z or A-Z.
So your current regexp matches strings like "." and "Hi." but not "Hi"
Try this: var pattern = /[^\w"!&,'\\-]/;
Note: \w also includes _, so if you want to avoid that then try
var pattern = /[^a-z0-9"!&,'\\-]/i;
I think the issue with your regex is that A-z is being understood as all characters between 0x41 (65) and 0x7A (122), which included the characters []^_` that are between A-Z and a-z. (Z is 0x5A (90) and a is 0x61 (97), which means the preceding characters take up 0x5B thru 0x60).
Related
This question already has answers here:
Including a hyphen in a regex character bracket?
(6 answers)
Closed 4 years ago.
I want to validate user's input and i use the following (which works fine) as regex.
pattern = /^[a-zA-Z0-9 .,!?;-]+$/;
But when i try with all the characters i want, which is this.
pattern = /^[a-zA-Z0-9 .,!?;-:()#'+=/]+$/;
It doesn't work and I dont know why. Also, I would appreciate it a lot if you explained to me what's the difference when I add the ^ and the +$. Also i have tried using \s instead of space, and it still doesn't work(I prefer just space because i want to restrict line change).
The "hyphen-minus" character, -, has special meaning within a character set (a set of characters between [ and ]). It, -, defines a range of characters. Most of the time in a character set that you want the - to represent itself, you need to use \- to escape its special meaning. In your use, - needs to be escaped \- when used between ; and :.
Working:
pattern = /^[a-zA-Z0-9 .,!?;\-:()#'+=/]+$/;
If you actually want the range of characters between : and ;, then you need to specify the one that has a lower character code (Ascii code chart, or Unicode) first. In this case, that means :-; as : comes before ;:
Show :-; range is valid:
pattern = /^[a-zA-Z0-9 .,!?:-;()#'+=/]+$/;
The same error would be generated if you were to try to specify a range such as z-a.
Show same error with range of z-a:
pattern = /^[z-aA-Z0-9 .,!?:-;()#'+=/]+$/;
The - does not take on its special meaning if it is the first or last character in the character set.
Note: In some regular expression implementations, the - does have its special meaning if you try to use it as the last character in the character set. You are better off just being in the habit of escaping it with \-.
Using - as first or last character in character set:
pattern = /^[-a-zA-Z0-9 .,!?;:()#'+=/]+$/;
pattern = /^[a-zA-Z0-9 .,!?;:()#'+=/-]+$/;
Original code with error:
pattern = /^[a-zA-Z0-9 .,!?;-:()#'+=/]+$/;
I want to strip everything except alphanumeric and hyphens.
so far i've got this but its not working:
String = String.replace(/^[a-zA-Z0-9-_]+$/ig,'');
any help appreciated?
If you want to remove everything except alphanum, hypen and underscore, then negate the character class, like this
String = String.replace(/[^a-zA-Z0-9-_]+/ig,'');
Also, ^ and $ anchors should not be there.
Apart from that, you have already covered both uppercase and lowercase characters in the character class itself, so i flag is not needed. So, RegEx becomes
String = String.replace(/[^a-zA-Z0-9-_]+/g,'');
There is a special character class, which matches a-zA-Z0-9_, \w. You can make use of it like this
String = String.replace(/[^\w-]+/g,'');
Since \w doesn't cover -, we included that separately.
Quoting from MDN RegExp documentation,
\w
Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_].
For example, /\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."
To check alphanumeric with special characters
var regex = /^[a-zA-Z0-9_$#.]{8,15}$/;
return regex.test(pass);
But, above regex returns true even I pass following combination
asghlkyudet
78346709tr
jkdg7683786
But, I want that, it must have alphanumeric and special character otherwise it must return false for any case. Ex:
fg56_fg$
Sghdfi#90
You can replace a-zA-Z0-9_ with \w, and using two anchored look-aheads - one for a special and one for a non-special, the briefest way to express it is:
/^(?=.*[_$#.])(?=.*[^_$#.])[\w$#.]{8,15}$/
Use look-ahead to check that the string has at least one alphanumeric character and at least one special character:
/^(?=.*[a-zA-Z0-9])(?=.*[_$#.])[a-zA-Z0-9_$#.]{8,15}$/
By the way, the set of special characters is too small. Even consider the set of ASCII characters, this is not even all the special characters.
The dollar sign is a reserved character for Regexes. You need to escape it.
var regex = /^[a-zA-Z0-9_/$#.]{8,15}$/;
I'm trying to create a validation for a password field which allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
I can't seem to get the hang of it.
What's the difference when using regex = /a-zA-Z0-9/g and regex = /[a-zA-Z0-9]/ and which chars from .!##$%^&*()_+-= are needed to be escaped?
What I've tried up to now is:
var regex = /a-zA-Z0-9!##\$%\^\&*\)\(+=._-/g
but with no success
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]+$/g
Should work
Also may want to have a minimum length i.e. 6 characters
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]{6,}$/g
a sleaker way to match special chars:
/\W|_/g
\W Matches any character that is not a word character (alphanumeric & underscore).
Underscore is considered a special character so
add boolean to either match a special character or _
What's the difference?
/[a-zA-Z0-9]/ is a character class which matches one character that is inside the class. It consists of three ranges.
/a-zA-Z0-9/ does mean the literal sequence of those 9 characters.
Which chars from .!##$%^&*()_+-= are needed to be escaped?
Inside a character class, only the minus (if not at the end) and the circumflex (if at the beginning). Outside of a charclass, .$^*+() have a special meaning and need to be escaped to match literally.
allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
Put them in a character class then, let them repeat and require to match the whole string with them by anchors:
var regex = /^[a-zA-Z0-9!##$%\^&*)(+=._-]*$/
You can be specific by testing for not valid characters. This will return true for anything not alphanumeric and space:
var specials = /[^A-Za-z 0-9]/g;
return specials.test(input.val());
Complete set of special characters:
/[\!\#\#\$\%\^\&\*\)\(\+\=\.\<\>\{\}\[\]\:\;\'\"\|\~\`\_\-]/g
To answer your question:
var regular_expression = /^[A-Za-z0-9\!\#\#\$\%\^\&\*\)\(+\=\._-]+$/g
How about this:-
var regularExpression = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,}$/;
It will allow a minimum of 6 characters including numbers, alphabets, and special characters
There are some issue with above written Regex.
This works perfectly.
^[a-zA-Z\d\-_.,\s]+$
Only allowed special characters are included here and can be extended after comma.
// Regex for special symbols
var regex_symbols= /[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.##]/;
This regex works well for me to validate password:
/[ !"#$%&'()*+,-./:;<=>?#[\\\]^_`{|}~]/
This list of special characters (including white space and punctuation) was taken from here: https://www.owasp.org/index.php/Password_special_characters. It was changed a bit, cause backslash ('\') and closing bracket (']') had to be escaped for proper work of the regex. That's why two additional backslash characters were added.
Regex for minimum 8 char, one alpha, one numeric and one special char:
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[!##$%^&*])[A-Za-z\d!##$%^&*]{8,}$/
this is the actual regex only match:
/[-!$%^&*()_+|~=`{}[:;<>?,.##\]]/g
You can use this to find and replace any special characters like in Worpress's slug
const regex = /[`~!##$%^&*()-_+{}[\]\\|,.//?;':"]/g
let slug = label.replace(regex, '')
function nameInput(limitField)
{
//LimitFile here is a text input and this function is passed to the text
onInput
var inputString = limitField.value;
// here we capture all illegal chars by adding a ^ inside the class,
// And overwrite them with "".
var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
limitField.value = newStr;
}
This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.
This works for me in React Native:
[~_!##$%^&*()\\[\\],.?":;{}|<>=+()-\\s\\/`\'\]
Here's my reference for the list of special characters:
https://owasp.org/www-community/password-special-characters
If we need to allow only number and symbols (- and .) then we can use the following pattern
const filterParams = {
allowedCharPattern: '\\d\\-\\.', // declaring regex pattern
numberParser: text => {
return text == null ? null : parseFloat(text)
}
}
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