How to identify the type of data that the user typed in a prompt or input?

2

I started studying JS for 3 weeks and I'm really apprentice ...

My greatest doubt is that I do not know an operator or command to identify and condition the value of the type of data entered by the user, for example:

var userValue = prompt("Digite um valor numérico");

    if(typeof userValue == "string"){
        alert("Você precisa digitar um valor numérico para prosseguir");
        return false;
    }
    else{
        alert("Ok, vamos prosseguir");
        ...codigo...
    }

As you can see I've used it I tried to use typeof to identify ... in case if it is string it will return false ...

It turns out that anything I type in prompt it interprets as string ...

It is also no use using parseInt or + at prompt because there it always interprets as number the value entered ...

What could I do in this case?

Thank you in advance for your attention ^^

    
asked by anonymous 19.09.2014 / 21:48

1 answer

2

If you want to ensure that what the user entered can be treated as a number, the parseInt and Number functions help you. If what the user entered can not be converted to number, you will get the value NaN ( not a number ).

Note that parseInt discards non-numeric parts of text.

A secure way to validate:

var foo = prompt("");
if (Number(foo) == foo) {
    // o input é todo numérico.
} else {
    // o input não é completamente numérico.
}
    
19.09.2014 / 22:02