javascriptjqueryjquery-mask

How to mask everything except last digit


I am trying to mask everything except last digit using jquery mask but I am not able to get the logic to do it. Below is what I tried so far.

$(document).ready(function() {
    var options = {
        onKeyPress: function(value, event, currentField, options) {
            var fieldVal = currentField.val();
            var star = '';
            for (var i = 0; i < fieldVal.length - 1; i++) {
                star += '*';
            }
            currentField.val(currentField.val().replace(/(.)(?!$)/g, star));
        }
    }
    $('.phone').mask('00000', options);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script>
<div>
    <input type="text" class="phone" />
</div>


Solution

  • The problem you are facing is related to the applied mask, you are using 00000, and a 0 only accepts a digit as input on that position. You will need to add a custom translation, as mentioned here, in the options.

    For generate the new value of the input I will use String.replace() with a custom replacement function to replace all characters by * except the last one.

    Example:

    $(document).ready(function()
    {
        var options = {
            translation: {0: {pattern: /[0-9*]/}},
            onKeyPress: function(val, evt, currField, options)
            {
                let newVal = val.replace(/./g, (m, o, str) => (o !== str.length - 1 ? '*' : m));
                currField.val(newVal);
            }
        };
    
        $('.phone').mask('00000', options);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script>
    <div>
        <input type="text" class="phone" />
    </div>