jquery.maskedinput allow optional characters in middle of mask?

Corey Ogburn picture Corey Ogburn · Dec 16, 2013 · Viewed 9.8k times · Source

I have asimple text box that has the following mask:

$('#txt_DateOfBirth').mask('99/99/9999');

It is sometimes loaded programmatically with a proper date that doesn't exactly match the mask (i.e. a single digit month or day). If it is loaded with a date like that, as soon as the input box has focus, it reverts back to __/__/____. If changes are made or not, when the input box loses focus the dynamically loaded date comes back. It's being set by:

$('txt_DateOfBirth').val(date); // example: date holds "12/1/1949" as string

Because the date does not perfectly match the mask it seems to break masked input. How can I add optional characters to the middle of a mask?

Answer

Kevin picture Kevin · Dec 16, 2013

Which plugin are you using? I'm guessing that your using Bush's inputmask. You can define your own masks, like you did in the comment but I don't think you can define optional parts (other than defining a mask for each case).

You may want to take a look at RobinHerbots mask (it's based on Bush's mask, so should be trivial to convert).

The nice thing about Robin's masking plugin is that you can define optional characters in a mask (or multiple masks, for that matter)

You should be able to do the following (characters in brackets are optional)

$('txtDateOfBirth').inputmask({ mask: '[9]9/[9]9/9999' });