+ 3

Help making my JavaScript code better! (Answered)

I am try to us JavaScript to validate a user input. but i am try to get it to only allow numbers. i have found one way to do it but it will be very repetitive and was wondering if there is a better way to go at this. you can see the live code here: http://metrikcorp.com/test/rate/index.php function validateForm() { var x = document.forms["Rating"]["Number"].value; if (x == "" || x >= 6 || x == 0) { document.getElementById("ERROR").innerHTML="Please Enter A Rating 1(bad) , 5(goo

26th Nov 2016, 8:33 PM
Metrik 🕵
Metrik 🕵 - avatar
6 Réponses
+ 4
Thanks alexyork That way was a great solution. Very simple just what i was looking for!
26th Nov 2016, 9:36 PM
Metrik 🕵
Metrik 🕵 - avatar
+ 2
instead of (if or) you can check the data type of x with typeof x if x is a number it will return number all you need to do is check if x == 'number' else alert user . var valtypex = typeof x; if (valtypex != 'number') { document.getElementById("ERROR").innerHTML="Please Enter A Number"; return false; }
26th Nov 2016, 8:55 PM
S1M0
S1M0 - avatar
+ 2
in general, in html added a new input type - number. in this input you can only enter numbers <input type="number">
26th Nov 2016, 9:02 PM
alexyork
alexyork - avatar
0
maybe try a Math.floor(). Example : Math.floor(3.17463) >> 3
26th Nov 2016, 8:43 PM
alexyork
alexyork - avatar
0
no problems bro)
26th Nov 2016, 10:10 PM
alexyork
alexyork - avatar
0
if you want to go another route, better for all cases of input (strings that are numbers, etc) try RegEx! if(x.test(/^(0|[1-9][0-9]*)$/)) { // code }
27th Nov 2016, 8:59 AM
Jared Allard
Jared Allard - avatar