Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

javascript - Restricting text box inputs to a given regexp using jQuery

Consider the following text box:

<input type="text" name="quantity" id="quantity_field" />

Using jQuery I want to restrict the set of valid inputs into quantity_field by the following regexp:

<script>
  var quantityRegexp = "^(0|[1-9]+[0-9]*)$";
</script>

More specifically I want to make the browser discard any characters entered into quantity_field that would make the value of the text field not conform to the given regexp. (A corresponding check would of course also be made on the server-side.)

Examples:

  • If the user types "foo 234" only "234" would get entered in the text box.
  • If the user types "001230" only "1230" would get entered in the text box.
  • If the user types "foo1bar" only "1" would get entered in the text box.

Question: What is the simplest way to acheive this using jQuery?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not an answer to your question (since I have no knowledge of jQuery), but the regex ^[1-9]*[0-9]*$ might not do as you expect or think. It matches empty strings but also a number like 000000. I expect that you don't want that since your first character class [1-9] explicitly ignores the zero. I think you should change the first * into a +: ^[1-9]+[0-9]*$. However, that regex will reject the (single) number 0. If you want to include that, you should do: ^(0|[1-9]+[0-9]*)$.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...