3

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?

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
  • Here is an old question that will solve your problem one way - http://stackoverflow.com/questions/15371025/jquery-masked-input-have-only-first-number-optional-rest-mandatory. Another way to do would be to format ALL dates with leading zeros before they are put into the mask. – TimSPQR Dec 16 '13 at 18:17
  • I tried setting it like so: `$.mask.definitions['~'] = '[0-9]?'; $('#txt_DateOfBirth').mask('~9/~9/9999');` but it still behaves the same. No change. – Corey Ogburn Dec 16 '13 at 18:23

1 Answers1

5

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' });
Kevin
  • 2,752
  • 1
  • 24
  • 46
  • Answering the question, pointing to another plugin, does not solve the problem. – MarceloBarbosa May 16 '16 at 20:09
  • 1
    @MarceloBarbosa This is a 3 year old question. The plugin OP was _already_ using doesn't support the feature they were seeking, and is for the most part deprecated. The newer version of the plugin which I recommended does. I didn't only post a link to the updated plugin, but showed him how to do it. – Kevin May 16 '16 at 21:35
  • Thanks for sharing. This answer worked for me with the same plugin as the OP https://stackoverflow.com/a/53320320/5429657 – Wesley Aug 22 '22 at 21:38