How to keep a suffix while masking a input using jQuery

1.8k Views Asked by At

I'm trying to mask a user input with the following mask "########-##.####.7.09.009" using jQuery, so when the user starts typing it would go like this:

1______-__.____.7.09.009 (user typed 1)

12_____-__.____.7.09.009 (user typed 2)

123____-__.____.7.09.009 (user typed 3)

and so on until it reaches the "7.09.009" part.

The user should not be able to edit that part, it is like a fixed placeholder there. I've tried using Jasny's input mask with some success but since numbers are masked with 0's and the fixed suffix has 0's, it allowed the user to type where there are zeroes in the fixed part. I did not find a way to replace the numbers placeholder from 0 to something else, as I imagine that would have solved my problem.

Then I found another jQuery mask plugin that allows me to mask numbers using # but as it also recognizes 0's as a placeholder for numbers, it ended up not working. I also tried creating a custom mask like so:

 $("#numero-processo").mask('0000000-00.0000.A.BC.BBC',
          {placeholder: "_______-__.____.7.09.009",
          'translation': {
               A: {pattern: /[7]/},
               B: {pattern: /[0]/},
               C: {pattern: /[9]/}
           }});

This worked to some extent, but when the user reached the fixed suffix part, (he/she) would have to actually type the suffix "7.09.009", and that is the only thing that would be allowed there because of the custom mask. However, I do not want the user to type the suffix, it needs to be fixed there. Does anyone know how to accomplish this? Thank you.

3

There are 3 best solutions below

0
On BEST ANSWER

You could accomplish this using this library

<script src="https://rawgit.com/RobinHerbots/Inputmask/4.x/dist/jquery.inputmask.bundle.js"></script>

Your javascript would be:

<input id="numero-processo" placeholder="_______-__.____.7.09.009" />

<script>
  $(document).ready(function(){
     $("#numero-processo").inputmask("9999999-99.9999.7.0\\9.00\\9");
  });
</script>

Here's a jsfiddle: https://jsfiddle.net/3kyau2p8/

1
On

You usually solve this by letting the fixed part outside the input (if the user shouldn't modify it, it's more ergonomic if it's actually not in the alterable part).

<input type="text" />.7.09.009

You can make it nicer with some css around, and you'll have to add it in JS or in the language you use to process the data. So maybe something like that :

<div class="mask_field" addendum=".7.09.009"><input type="text" />.7.09.009</div>

Could be easier to work with.

1
On
$("#numero-processo").keyup(function(){
    var input = $(this).val();
    if(input.length == 15) {
        input += ".7.09.009";
        $(this).val(input);
    }
});