Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fix the character 'A' in a JQuery-mask?

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

like image 952
Eric Scaglioni Avatar asked Oct 15 '22 13:10

Eric Scaglioni


1 Answers

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>
like image 56
gaetanoM Avatar answered Oct 19 '22 01:10

gaetanoM