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?

4
  • 3
    An inputs value is always of type string, you should be using isNaN to check for numeric values. Commented Mar 10, 2016 at 21:33
  • You might be better off using a regular expression to validate your input, depending on what you want to allow. Commented Mar 10, 2016 at 21:35
  • Possible duplicate of Is there a (built-in) way in JavaScript to check if a string is a valid number? Commented Mar 10, 2016 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 Commented Mar 11, 2016 at 16:02

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.