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

145
Visualizações
Validate Form With JavaScript Using Multiple id

I use JavaScript to validate my form but the JavaScript can only validate a field at a time which means I have to duplicate the JavaScript for every field that I want to validate.

For Example,

My form has the Phone and Email fields that I want to validate, To achieve that, I had to write the javascript with the phone ID separately and write the javascript with the email ID separately.

Is it possible to validate the phone and email fields independently but with one javascript file and different ids?

My Sample code is below;

<!--THIS SCRIPT ONLY VALIDATES THE PHONE FIELD -->

<!--TO VALIDATE THE EMAIL FIELD, I HAVE TO DUPLICATE THIS SCRIPT AND CHANGE THE IDS TO email -->

$('.validate').hide();
$('body').on('blur', '#phone', function() {
  var value = $(this).val();
  if (isphoneInUse(value)) {
 alert ("Phone In Use!\nPlease provide another one");
    $(".validate").hide();
  } else {
    $(".validate").show();
  }
});
$('#submitForm()').on('submit', function(e) {
  var value = $("#phone").val();
  if (isphoneInUse(value)) {
    // validation failed. cancel the event
    console.log("not submitting");
    return 0;
  }
})

function isphoneInUse(phone) {
  return (phone === "1234" || phone === "23456")
}
  
 <script src="https://code.jquery.com/jquery-1.12.4.js"></script>


<form action='' method='POST' id="submitForm" runat="server" >
   
    <div class="validate" style="display: none;"><span style="color: #4ead55; font-size: x-small;"><b>Phone Available ✓</b></span></div>
 
 <input type="phone" name='phone'  required=''  id="phone" placeholder="0000-000-0000"/>

<br/><br/>

 <div class="validate2" style="display: none;"><span style="color: #4ead55; font-size: x-small;"><b>Email Available ✓</b></span></div>

<input type="email" name='email' required='' id="email" placeholder="hello@youremail.com"/>
        </div>
 <br/><br>
 <button class="button" id="submitForm" type="submit" value=""><span>Check </span></button>

</form>

about 4 years ago · Juan Pablo Isaza
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