Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
How to validate user name with regular expression

I'd want to validate a username using a regular expression, however the expression I used worked well on https://regexr.com/  but not in my code. I just want user can add only Alphanumeric and a space between them

var letters = /^[A-Za-z]+$/g;

function validate() {
  var input = document.getElementById("fname").value;
  if (input.match(letters)) {
    document.getElementById("name").innerHTML = "** Only alphabets are allowed in name.";
    return false;
  }
}
<input id="fname">
<input type="button" onclick="validate()" value="Check">
<br>
<span id="name"></span>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your current function is "finding alphanumeric characters". So, when you run validate(), it is returning either a valid Array, or null. To get spaces use /^[\w\-\s]+$/ although this will return true for multiple spaces. I'm not sure your use case.

Unless you want to change your regex, you need to show your warning when input.match() returns a falsey value. To do this, Place ! before your input.match() function

var letters = /^[\w\-\s]+$/;

function validate() {
  document.getElementById("name").innerHTML = "";

  var input = document.getElementById("fname").value;

  if (!input.match(letters)) {
document.getElementById("name").innerHTML = "** Only alphabets are allowed in name.";
return false;
  }
}
<input id="fname">
<input type="button" onclick="validate()" value="Check">
<br>
<span id="name"></span>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda