I'm trying to check if a string contains certain characters. I was going to use regex, but my string may not have a format.
I would like to ensure that i'm allowing only the following characters
1. + symbol 2. - symbol 3. numbers 0~9 4. ( 5. ) 6. . (dot) 7. spaces
I'm trying to check if a string contains certain characters. I was going to use regex, but my string may not have a format.
I would like to ensure that i'm allowing only the following characters
1. + symbol 2. - symbol 3. numbers 0~9 4. ( 5. ) 6. . (dot) 7. spacesShare Improve this question edited Jun 16, 2011 at 21:35 Dan 1,88813 silver badges17 bronze badges asked Jun 16, 2011 at 21:28 MoonMoon 22.6k72 gold badges197 silver badges273 bronze badges 3
- 2 What do you mean, your "string may not have a format"? What are you validating exactly? – Eevee Commented Jun 16, 2011 at 21:31
- Can you elaborate what you mean when you say "may not have a format"? – Dan Commented Jun 16, 2011 at 21:32
- 1 Possibly "but I can't work out what to put in the regex to make it work"? – Bojangles Commented Jun 16, 2011 at 21:37
3 Answers
Reset to default 10This regex will match a string containing only those characters:
^[+\-0-9(). ]+$
Working Demo
if ( string.match('[^(). +\-0-9]') ) {
alert("Invalid string");
}
Try this:
var isValid = /^[\x2B\x2D\x28\x29\x2E\s\d]+$/.test(input);
if(isValid ) {
//...
} else {
//..invalid
}