3

I'm trying to make a JavaScript program where you enter a numeric value into an input field, and then the program returns a message based on what number you entered.

There are two main parameters with the number input field I want to have:

1. The number you enter in the field must be between 0-100, and if it's not then an alert will be called telling you to enter a proper value.

I have done that, but it's the next parameter I'm having trouble with.

2. You may only enter numeric values into the input field. If you don't (e.g. you enter an alphabetical character) then an alert will be called saying that you may only enter numbers.

Both of these parameters are checked off when the user clicks a button; the button calls some functions that do this. I'm having problems with the second parameter, however.

I can't figure out how I can get the program to look at the what the user typed and determine if any values in it are alphabetical characters (letters).

So, to recap, my overall question is this: How can I check if any characters that are inputted into a number field are alphabetical letters, through a function that is called with a button?

If my question is confusing at all please tell me and I will try to clarify. Any help would be greatly appreciated. Thanks.

  • are you targeting newer browsers only, those who support html5? – Asons Sep 20 '15 at 07:50
  • @LGSon Yes, I'm using HTML5, however, I'm not actually publishing the webpage; I'm just practicing JS. I use the newest version of Mozilla Firefox, which supports HTML5. – Nick Mitchell Sep 20 '15 at 07:53
  • This post has all the answers you need ... http://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input – Asons Sep 20 '15 at 07:55
  • Thanks. I'll have a look. Sorry for duplicating a question. – Nick Mitchell Sep 20 '15 at 07:58
  • You're welcome and don't be sorry, people use different ways to express themselves and we try to navigate them to a good answer, which sometimes have multiple questions. – Asons Sep 20 '15 at 08:01

2 Answers2

0

You can use an input element of type number and the browser will prevent the user from entering letters.

<input type="number" name="quantity" min="1" max="5">

Not all browsers will restrict the input though. Chrome at least still allows 'e' to be typed.

Otherwise you can use a regex to check if the input contains only numbers.

var has = /[0-9]/.test('12341');
toskv
  • 30,680
  • 7
  • 72
  • 74
0

To the RegExMobile!

var goodInput = "3456"
var badInput  = "34g8"
var regex = new RegExp(/[^0-9]/g);

console.log(goodInput.test(/[^0-9]/g)) // false
console.log(badInput.test(/[^0-9]/g)) // true
Adrian Lynch
  • 8,237
  • 2
  • 32
  • 40