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

64
Visualizações
Validation issues in Javascript

The following function is supposed to check two inputs: name and message. Im not sure what is wrong here but Im trying to first see if the input is empty if its not I want to then check it with a regular expression. The message I just want to see if it is empty or not. If either are empty I want to return a message asking to enter the correct input. Im not sure if I should use else ifs here or separate if statements altogether. If Im doing this completely bonkers Id like to know that as well. thanks!

Javascript:

function validate() {
  let regName = /^[a-zA-Z]+ [a-zA-Z]+$/;
  let name = document.querySelector("[name='user-name']");
  let msg = document.querySelector("[name='user-message']");
  
  if (name) {
      name = name.value;   
  } else if (!regName.test(name)){
    document.querySelector("[name='user-name']");
    return "Please enter your first & last name.";    
  }

  if (msg) {
      msg = msg.value;
  } else if (msg.trim() == "") {     
    document.querySelector("[name='user-message']");
    return "Please enter a message";
  } 
} 
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your if and else if logic is wrong. You're only performing the regexp test when the input element can't be found by document.querySelector(). else if only runs when the previous condition failed.

You should put that check in the same if that checks that the input was found.

function validate() {
  let regName = /^[a-zA-Z]+ [a-zA-Z]+$/;
  let name = document.querySelector("[name='user-name']");
  let msg = document.querySelector("[name='user-message']");

  if (name && !regName.test(name.value)) {
    return "Please enter your first & last name.";
  }

  if (msg && msg.value.trim() == "") {
    return "Please enter a message";
  }
}

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