Regex code in javascript for restricting input fie

2019-08-21 11:11发布

I have a question about restricting the value entered in some input field. I would like to input this :

9digits-whatever, for example 101010101-Teststring.

I have come up with this regex as a solution, but it does not seem to be correct:

^\d{9}\-[a-zA-Z0-9_]*$

Any ideas on this one?

Thank you.

2条回答
倾城 Initia
2楼-- · 2019-08-21 11:48

The below regex would match 9 digits follwed by - and any number of characters.,

^\d{9}-.*$

If you want a minimum of one character followed by -, then try the below regex.

^\d{9}-.+$

Explanation:

  • ^ Asserts that we are at the beginning of the line.
  • \d{9} Exactly 9 digits.
  • \- Literal - symbol.
  • .* Matches any character zero or more times.
  • $ End of the line.
查看更多
贪生不怕死
3楼-- · 2019-08-21 12:05
  • There is no need to escape hyphen -.
  • Use \w that include [a-zA-Z0-9_]

Try below regex if there is only [a-zA-Z0-9_] after 9 digits and hyphen.

^\d{9}-\w*$

Online demo

查看更多
登录 后发表回答