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

247
Visualizações
How to validate a zipcode text field and add HTML in case of error on submitting the form?

The jQuery code below alerts the user in case of incorrect zip code entered by attaching the change event to it. I would like to validate zip code entered in the text field on form in a landing page and add a bit of HTML in case of error on submitting the form. Could you please guide me on how to do it.

HTML for the input:

<div class="ff-el-input--content"><input type="text" name="address_1[zip]" id="ff_241_address_1_zip_" class="ff-el-form-control" placeholder="Zip"></div>

jQuery to validate:

jQuery("input:text[name='address_1[zip]']").change(function(e) {
if (!jQuery(this).val().match(/^\d{5}(?:[-\s]\d{4})?$/)) { 
        alert("Please enter a valid zip code");
        jQuery("input[name='address_1[zip]']").val("");
        return false;                        
    }        
});

When validation fails, I need to add the div below to right after the input text field. <div class="error text-danger">This field is required</div>

Submit element:

<button type="submit" class="ff-btn ff-btn-submit   ff-btn-lg">Submit</button>

Image showing part of the form: enter image description here

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

0

What you need are the functions after() and remove().

jQuery("input:text[name='address_1[zip]']").change(function(e) {
  if (!jQuery(this).val().match(/^\d{5}(?:[-\s]\d{4})?$/)) {
    alert("Please enter a valid zip code");
    jQuery("input[name='address_1[zip]']").val("");
    if ($('.error').length == 0) {
      $(this).after('<div class="error text-danger">This field is required</div>');
    }
  } else {
    $('.error').remove();
  }
});
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