最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to validate a string contains certain characters? - Stack Overflow

programmeradmin3浏览0评论

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

Share 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
Add a comment  | 

3 Answers 3

Reset to default 10

This 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
  }
发布评论

评论列表(0)

  1. 暂无评论