Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Javascript Regex

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.

like image 950
SkelDave Avatar asked Jul 30 '14 14:07

SkelDave


People also ask

Does regex work in JavaScript?

In JavaScript, you can write RegExp patterns using simple patterns, special characters, and flags.

What is basic regex?

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.

Is regex fast JavaScript?

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.

How do you use regex?

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).


1 Answers

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")
like image 173
Pointy Avatar answered Nov 15 '22 09:11

Pointy