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

159
Visualizações
Change Zip Code Regex Pattern via JS or Jquery based on Country Select

I can return a (HTML5) validation error using the following script but now I'm at a loss on how to 'if/else if' based on the Country.

Goal Javascript/Jquery to validate zip code based on selection of country prior to form submission using the validation patterns (99999 or A9A 9A9).

If visitor chooses US set the pattern for 99999. Else if chooses Canada set the pattern for A9A 9A9.

$('p.zip').each(function() {
  $(this).find("input").prop('pattern', '\d{5}(?:-\d{4})?|[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <p class="country">
    <label class="field-label" for="13037">Country</label>
    <select name="13037" id="13037" class="select" onchange="">
      <option value="" selected="selected"></option>
      <option value="47917">US</option>
      <option value="47919">Canada</option>
    </select>
  </p>
  <p class="form-field group-contact col3 row3  form-row-half-sm zip pd-text required    ">
    <label class="field-label" for="13001">Zip Code</label>
    <input type="text" name="13001" id="13001" value="" class="text" size="30" maxlength="32" onchange="" onfocus="">
  </p>
  <button>Submit</button>
</form>

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

0

You want to add reset your validator every time the select option changes. Something like:

    function countryChanged() {
      var countryId = $( this ).val();
      
      var regexExp = '\d{5}(?:-\d{4})?|[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d';
      
      switch(countryId)
      {
         case '47919' : regexExp = 'regex for CANADA here';
         break;
      
      }
      
      changeValidator(regexExp);
    }
    
    function changeValidator(regexExp) {
      $('p.zip').each(function() {
        $(this).find("input").prop('pattern', regexExp);
      });
    }
    
    
    $( "#13037" ).change(countryChanged);
    
    countryChanged();
about 4 years ago · Juan Pablo Isaza Relatório

0

I have a solid solution in case this helps anyone

// var zipPlaceholderFormat = 'xxxxx'; //default to US placeholder format
var zipPattern = /^[0-9]{5}$/; //default to US regex format
var zipErrorMessage = 'Please enter a valid zip code'

// by default, set the country to US
if ($('p.country select').val() === '') {
  $('p.country select').val($('p.country select option:contains("US")').val());
}

$('p.country select').change(function() {
  // zipPlaceholderFormat = 'xxxxx'; //default to US placeholder format
  zipPattern = /^[0-9]{5}$/; //default to US regex format
  zipErrorMessage = 'Please enter a valid zip code'

  switch ($(this).find('option:selected').text()) {
    case 'Canada':
      // zipPlaceholderFormat = 'A9A 9A9'
      zipPattern = /^[A-Za-z][0-9][A-Za-z] [0-9][A-Za-z][0-9]$/;
      zipErrorMessage = 'Please enter a valid postal code';
      $('p.Province_Canada select').change();
      break;
    default: // US
      $('p.state select').change();
  }

  // $('p.zip input').each(function() {
  //     $(this).prop('placeholder', zipPlaceholderFormat);
  // });
}).change();

// checks the zip/postal code based on value provided by visitor
$('p.zip input').change(function(event) {
  var zipValue = $(this).val(); //get the current value from form
  var match = zipValue.match(zipPattern)
  $('p.zip span.error').remove();
  if (zipValue && match) {
    $(this).removeClass('invalid');
  } else if (!zipValue) {
    $(this).removeClass('invalid');
  } else {
    $(this).parent().append('<span id="notify" class="error no-label text">' + zipErrorMessage + '</span>');
    $(this).addClass('invalid');
  }
}).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <p class="country">
    <label class="field-label" for="13037">Country</label>
    <select name="13037" id="13037" class="select" onchange="">
      <option value="" selected="selected"></option>
      <option value="47917">US</option>
      <option value="47919">Canada</option>
    </select>
  </p>
  <p class="form-field group-contact col3 row3  form-row-half-sm zip pd-text required    ">
    <label class="field-label" for="13001">Zip Code</label>
    <input type="text" name="13001" id="13001" value="" class="text" size="30" maxlength="32" onchange="" onfocus="">
  </p>
  <button>Submit</button>
</form>

else.

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