Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery zip masking for multiple formats

I have a requirements for masking a zip field so that it allows the classic 5 digits zip (XXXXX) or 5 + 4 format (XXXXX-XXXX).

I could so something like:

$('#myZipField').mask("?99999-9999");

but the complication comes from the fact that dash should not be showing if the user puts in only 5 digits.

This is the best I came up with so far - I could extend it to auto-insert the dash when they insert the 6th digit but the problem with this would be funny behavior on deletion (I could stop them from deleting the dash but it would patching the patch and so forth, it becomes a nightmare):

$.mask.definitions['~']='[-]';
$("#myZipField").mask("?99999~9999", {placeholder:""});

Is there any out of the box way of doing this or do I have to roll my own?

like image 463
JohnIdol Avatar asked Jun 24 '10 14:06

JohnIdol


2 Answers

You don't have to use a different plug-in. Just move the question mark, so that instead of:

$('#myZipField').mask("?99999-9999");

you should use:

$('#myZipField').mask("99999?-9999");

After all, it isn't the entire string which is optional, just the - and onward.

like image 70
Ansikt Avatar answered Sep 28 '22 17:09

Ansikt


This zip code is actually simple, but when you have a more complex format to handle, here is how it's solved with the plugin (from the demo page):

var options =  {onKeyPress: function(cep, e, field, options){
  var masks = ['00000-000', '0-00-00-00'];
    mask = (cep.length>7) ? masks[1] : masks[0];
  $('.crazy_cep').mask(mask, options);
}};

$('.crazy_cep').mask('00000-000', options);
like image 41
Piotr Salaciak Avatar answered Sep 28 '22 16:09

Piotr Salaciak