I want to validate a string in JavaScript to allow alphanumerics, "(", ")" , and spaces. So test strings are:
s1 = "This $h00l*&^ not w0rk342*_(&, <and> always fail"
s2 = "This should work (ABC1234)"
my code:
var regX = new RegExp(/A-Za-z0-9\\(\\)\\x20+/);
if(!regX.test(s1)){
alert("InValid value.");
}
But it fails for both the strings.
Also as test() function evaluates the matches in the string and not the whole string
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
Can someone please help. Thanks in advance
You should use this regex:
/^[A-Za-z0-9() ]*$/
Replace * with + if you don't want to allow empty string.
^ and $ test for beginning and the end of the string respectively.
* means repeat 0 or more times. + means repeat once or more.
To specify a character class (i.e. a set of character), you need to place the characters inside [].
To further shorten the regex:
/^[a-z\d() ]*$/i
i flag will make the regex matches case-insensitively, which remove the needs to specify A-Z.
\d is the shorthand character class for digits 0-9. Shorthand character class can also be included inside character class.
Related
I want a Regex for my mongoose schema to test if a username contains only letters, numbers and underscore, dash or dot. What I got so far is
/[a-zA-Z0-9-_.]/
but somehow it lets pass everything.
Your regex is set to match a string if it contains ANY of the contained characters, but it doesn't make sure that the string is composed entirely of those characters.
For example, /[a-zA-Z0-9-_.]/.test("a&") returns true, because the string contains the letter a, regardless of the fact that it also includes &.
To make sure all characters are one of your desired characters, use a regex that matches the beginning of the string ^, then your desired characters followed by a quantifier + (a plus means one or more of the previous set, a * would mean zero or more), then end of string $. So:
const reg = /^[a-zA-Z0-9-_.]+$/
console.log(reg.test("")) // false
console.log(reg.test("I-am_valid.")) // true
console.log(reg.test("I-am_not&")) // false
Try like this with start(^) and end($),
^[a-zA-Z0-9-_.]+$
See demo : https://regex101.com/r/6v0nNT/3
/^([a-zA-Z0-9]|[-_\.])*$/
This regex should work.
^ matches at the beginning of the string. $ matches at the end of the string. This means it checks for the entire string.
The * allows it to match any number of characters or sequences of characters. This is required to match the entire password.
Now the parentheses are required for this as there is a | (or) used here. The first stretch was something you already included, and it is for capital/lowercase letters, and numbers. The second area of brackets are used for the other characters. The . must be escaped with a backslash, as it is a reserved character in regex, used for denoting that something can be any character.
I have an input field that should only accept characters used in a currency syntax (dollar sign, numbers, commas, and decimals). How can I write my REGEX to check if a string contains atleast one character that is NOT from the above listed characters?
I've tried the following, but the problem with this expression is that if one valid character is present in the string it throws the 'else' statement. (unitPriceVal is the user input string)
I want to write a regex that checks if the WHOLE string consists of the valid Currency, if true run the else statement
validCurrency = /([0-9\$.,])/;
if (!unitPriceVal.match(validCurrency) || unitPriceVal == "") {
unitPrice.setValueState("Error");
} else {
unitPrice.setValueState("None");
}
},
I want to write a regex that checks if the WHOLE string consists of the valid Currency
To check the whole string, anchor the match to the beginning and end of the input, using ^ and $, and make sure what's in between is a sequence (+) of allowable characters:
/^[\d$.,]+$/;
You don't need parentheses. You also don't need to escape the $ inside the character set. Finally, you can use \d for a digit.
Often, it's better to use the input element's pattern attribute to do this check. In that case, you don't need the anchors (they're implied):
<input pattern="[\d$.,]+">
How can I write my REGEX to check if a string contains at least one
character that is NOT from the above listed characters?
function validUnitPrice(unitPriceVal) {
let invalidCurrency = /[^0-9\$.,]/;
return unitPriceVal.search(invalidCurrency) == -1;
}
The ^ character as the first character inside a character set ([^...]) negates the character set i.e. matching characters not in the set.
Good Day,
I'm creating a javascript function to exclude certain codes from the database.
For example, the following are valid codes:
FF99
1G499
RNDD
In other words, I want the codes to consist of only alphanumerics. I opened up the console in Chrome and tried:
> re = new RegExp('\w+')
> re.test('whatever')
true
> re.test('what???')
true
> var test = new RegExp('^\w+')
> test.test('what')
true
> test.test('what999')
true
> test.test('what???')
true
So I know that \w can either be a 0-9, a-z, A-Z. I don't know why the regex is passing if I enter '?' when they shouldn't.
Am I missing something?
You're misinterpreting your results. The regexp \w+ means "one or more word characters". It doesn't specify where in the string these characters can be found. In all of your tests, the provided string contains at least one word character, so they all pass.
What you're meaning to do is ensure the string contains only alphanumerics. Try the following regex:
^\w+$
Broken down, this means:
^ = match start of string
\w = letters or digits
+ = one or more of the previous element (in this case, the set) (this is greedy)
$ = match the end of the string
In English, this means, "between the start and end of the string, only alphanumeric characters will match. Match as many as possible, or none at all"
Documentation on ^ and $
Note: if you write your regex as a string, you need to escape the \ like so:
new RegExp("^\\w+$")
Otherwise, JavaScript will interpret \w as an escape sequence, which it is not. You can also use the syntax
new RegExp(/^\w+$/)
in which case you don't need to escape the \, since it isn't a string.
Test is returning true because the pattern \w+ is matching the alphanumeric part in your test strings.
re.test('what???') for example will return true because it matches what.
If you only want to match strings consisting of only alphanumeric characters, you should use something like ^\w+$ .
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 have a username field in my form. I want to not allow spaces anywhere in the string. I have used this regex:
var regexp = /^\S/;
This works for me if there are spaces between the characters. That is if username is ABC DEF. It doesn't work if a space is in the beginning, e.g. <space><space>ABC. What should the regex be?
While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:
var regexp = /^\S*$/; // a string consisting only of non-whitespaces
Use + plus sign (Match one or more of the previous items),
var regexp = /^\S+$/
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex #Bergi mentioned just the string version for new RegExp constructor
This will help to find the spaces in the beginning, middle and ending:
var regexp = /\s/g
This one will only match the input field or string if there are no spaces. If there are any spaces, it will not match at all.
/^([A-z0-9!##$%^&*().,<>{}[\]<>?_=+\-|;:\'\"\/])*[^\s]\1*$/
Matches from the beginning of the line to the end. Accepts alphanumeric characters, numbers, and most special characters.
If you want just alphanumeric characters then change what is in the [] like so:
/^([A-z])*[^\s]\1*$/