Enrique Padilla
Enrique Padilla

Reputation: 11

How to validate an input as an number in JavaScript

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?

Upvotes: 1

Views: 172

Answers (2)

Enrique Padilla
Enrique Padilla

Reputation: 11

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;
        }
    }

Upvotes: 0

Borys Serebrov
Borys Serebrov

Reputation: 16172

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.

Upvotes: 1

Related Questions