简体   繁体   中英

How to validate input text to ensure only floats or ints greater than a minimum value are entered?

I have an input tag of type text.

The user is supposed to enter a float or int, greater than 4. How to I verify that the user has not entered any non-numeric characters ? Decimal points are ok:

For example:

  1. 10.1 (ok)
  2. 10 (ok)
  3. 10$ (not ok)
  4. abcs (not ok)
  5. .0.12 (not ok -> Too many periods)
  6. 4 (not ok -> number must be greater than 4)
  7. 1a (not ok)

How do I do this? Parsing each and every character in the text box seems clumsy, and I'm don't know think I can do this with a regex. Any suggestions ?

Check out isNaN() and carefully read through how to use it. Until ECMA 6 is widely used, isNaN() is probably the best in conjunction with typeof .

Use parseFloat() :

Here's a JSFiddle example: http://jsfiddle.net/HbqF3/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM