7

I've been building a zip code component in ASP.NET MVC which will be globalized. Which means that according the supplier's country, the textbox will set the correct zip code's mask. The problem is that some countries have a 'A' character fixed in its mask. For example: Andorra's zip code is 'AD000' (my mask), where AD is fixed, followed by 3 digits. My component is dynamic, so I saved the masks by country in database and the view is rendered my component is able to set it. But the character 'A' is a reserved character in JQuery-mask, which means A-Z letter or a digit. So, when the country is Andorra my maks is not forcing user do enter A, the user can put anything and I don't want this behavior. What can I do?

I've seen somewhere that if I used '\' it would understand the next character as literal. But it didn't work

$('input.my-class').mask('AD000')

What I want is, when the user starts to digit, the component render AD automatically and then wait for the user put the digits

  • I would write my own mask plugin for this. Listen to events and enforce the input. – tiborK Jun 21 '19 at 13:22
  • By looking at the doc, I don't think it's possible. Looks like this has been asked on the github page here https://github.com/igorescobar/jQuery-Mask-Plugin/issues/295 – Carlos27 Jun 21 '19 at 13:27

1 Answers1

4

You can customize translation option. The default value is:

translation: {
  '0': {pattern: /\d/},
  '9': {pattern: /\d/, optional: true},
  '#': {pattern: /\d/, recursive: true},
  'A': {pattern: /[a-zA-Z0-9]/},
  'S': {pattern: /[a-zA-Z]/}
};

You need to change 'A' into:

{
    translation: {
        'A': {
            pattern: /A/,
            fallback: 'A',
            optional: false
        }
    }
 }

Where fallback stays for:

When a user types a invalid char for the current position the plugin will replace it by its fallback instead of erasing them.

$('input.my-class').mask('AD000', {
    translation: {
        'A': {
            pattern: /A/,
            fallback: 'A',
            optional: false
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/igorescobar/jQuery-Mask-Plugin@master/dist/jquery.mask.min.js"></script>


<form>
    <input type="text" name="field-name" class="my-class" />
</form>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • 1
    For anyone starting to use this plugin: `0` `9` `#` `A` `S` are all reserved characters for the plugin. If you want to bypass them, apply this answer to every one of them (as an this additional example: https://gist.github.com/carloswm85/28faae4f0a8f517943c4ba4bc54cc585 ). – carloswm85 Mar 30 '23 at 15:31