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

Asked

Viewed 111 times

2

I started studying JS 3 weeks ago and am well apprenticed...

My biggest current duplicitous is that I don’t know an operator or command to identify and condition the value of the data type entered by the user, 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 used tried to use the typeof to identify... in the case if string will return false...

It turns out anything I type into prompt he interprets as string...

There’s no point in using it either parseInt or + in the prompt because then he always interprets how number the entered value...

What could I do in this case?

Thank you from now on for your attention ^^

  • A number can always be a string, so it doesn’t help what you’ve done. But Cvoce knows that a number has no non-numeric characters other than '.' right? This should help.

  • 1

    I appreciate your answer, Lucas! But, in a + objective way, how should it look for the user to type letters return false and type number give true?

1 answer

2

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

Note that parseint discards non-numerical parts of the text.

A safe way to validate:

var foo = prompt("");
if (Number(foo) == foo) {
    // o input é todo numérico.
} else {
    // o input não é completamente numérico.
}
  • Right, parseint just forces the variable to be treated as number... I didn’t know the Number function, I’ll study + on it. Thanks for the attention :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.