Moon
Moon

Reputation: 22565

How to validate a string contains certain characters?

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

Upvotes: 4

Views: 23462

Answers (3)

Town
Town

Reputation: 14906

This regex will match a string containing only those characters:

^[+\-0-9(). ]+$

Working Demo

Upvotes: 10

The Mask
The Mask

Reputation: 17427

Try this:

  var isValid = /^[\x2B\x2D\x28\x29\x2E\s\d]+$/.test(input); 
  if(isValid ) {
      //...

  } else { 
    //..invalid
  }

Upvotes: 1

Jonathan Hall
Jonathan Hall

Reputation: 79516

if ( string.match('[^(). +\-0-9]') ) {
    alert("Invalid string");
}

Upvotes: 6

Related Questions