How to check if a variable is string or number?

Asked

Viewed 54 times

-2

I made a "mini site" to ask the name of the person and send a alert but somehow I want to send a alert error if the person places numbers instead of the characters in the name.

<h2 class="Titulo">Bem Vindo</h2>
   <div id="Maincx">
       <div class="dados-pessoa">
           <label for="nome">Digite seu Nome</label>
           <input type="text" id="name" name="name">
           <button onclick="submit()">Enviar</button>
       </div>
   </div>`
function submit() {
  var input = document.getElementById('name');
  var texto = input.value;

  console.log("Nome inserido: " + texto);

  alert("Olá Sr. " + texto + " Balalaika");
    
}
  • only use typeof(text) will return string

1 answer

0


There are some comments trying to guide the user to an answer, but I think none of them really help in this case.

To verify that what was typed in input was a string or a number, do not just check the type of the value, for the value will always be the string

In Javascript there is a function isNaN, which is used to check whether a variable nay is a number. It’s not just to check if the variable type is not number, it also validates whether strings are numerical representations, for example:

isNaN('Lukas') // true
isNaN('Luk4s') // true
isNaN('123')   // false
isNaN('1.0')   // false
isNaN('1e5')   // false - isso é uma representação válida do número 100000

Other alternatives would be to use regular expressions such as value.match(/[^0-9]/) to validate whether the value has at least one character other than a digit, or value.match(/^[^0-9]*$/) to validate whether the value has no digit.

Example:

function submit() {
  var input = document.getElementById('name');
  var texto = input.value;

  console.log("Nome inserido: " + texto);
  
  if (isNaN(texto)) {
    alert("Olá Sr. " + texto + " Balalaika");
  } else {
    alert("Por favor, digite um nome válido");
  }
}

Browser other questions tagged

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