Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda