1

I'm new with JavaScript programming and have been trying to validate a number that is inputted from a user on a php page. Here is the javascript that is included.

var validate_and_create = function(){
    var i_number = $("input_number").value;
    var isValid = true;

    if (i_number === ""){
        $("create_n_error").firstChild.nodeValue = "Number text field cannot be blank.";
        isValid = false;
    } else {
        if  (typeof i_number === 'number') {
            $("create_n_error").firstChild.nodeValue = "This is a number!";
            isValid = true;
        } else {
            $("create_n_error").firstChild.nodeValue = "This is not a number!";
            isValid = false;
        }
    }

It always prints that the input is not a number even when integer values are inserted in the textbox. So I'm sure its taking the input as a string input. So do I have to convert it to integer so I can validate? or am I doing something wrong?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 3
    An inputs value is **always** of type string, you should be using `isNaN` to check for numeric values. – adeneo Mar 10 '16 at 21:33
  • You might be better off using a regular expression to validate your input, depending on what you want to allow. – Dave Mar 10 '16 at 21:35
  • Possible duplicate of [Is there a (built-in) way in JavaScript to check if a string is a valid number?](http://stackoverflow.com/questions/175739/is-there-a-built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number) – Heretic Monkey Mar 10 '16 at 21:52
  • why not use the html5 `type=number`? The browser will take care of the validation and mobile users should get the correct, numeric, keyboard automatically – Pevara Mar 11 '16 at 16:02

2 Answers2

1

You can use parseInt to convert the value to integer, like parseInt("55", 10) will return 55.

And something like parseInt("xx",10) returns NaN.

Borys Serebrov
  • 15,636
  • 2
  • 38
  • 54
0

Thanks adeneo, isNaN works for validation.

Code below:

var validate_and_create = function(){
    var i_number = $("input_number").value;
    var isValid = true;

    if (i_number === ""){
        $("create_n_error").firstChild.nodeValue = "Number text field cannot be blank.";
        isValid = false;
    } else {
        if  (isNaN(i_number)) {
            $("create_n_error").firstChild.nodeValue = "This is not a number!";
            isValid = false;
        } else {
            $("create_n_error").firstChild.nodeValue = "This is a number!";
            isValid = true;
        }
    }