I'm trying to learn javascript Regex and I've hit a problem.
I'm trying to validate with the following rules.
Allow only:
Numbers 0-9
(
)
+
-
(space)
I have come up with the regex below to handle this:
/[0-9\)\(\+\- ]+/i
The following matches but shouldn't do because it contains a @ symbol:
+0@122 0012
I'm using the below to test: (Returns true)
/[0-9\)\(\+\- ]+/i.test("+0@122 0012")
Thanks.
In JavaScript, you can write RegExp patterns using simple patterns, special characters, and flags.
Regular Expressions/Basic Regular ExpressionsThe dot operator matches any single character. [ ] A box enables a single character to be matched against a character list or character range. [^ ] A compliment box enables a single character not within a character list or character range to be matched.
A regular expression (also called regex for short) is a fast way to work with strings of text. By formulating a regular expression with a special syntax, you can: search for text in a string.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
Your regular expression won't match the "@" character, but it doesn't have to in order for the .test()
call to return true
. There just has to be a match somewhere in the string.
If you want to insist that the entire string matches, you have to use ^
and $
anchors.
/^[0-9)(+ -]+$/i.test("+0@122 0012")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With