Mask Car plate in jQuery

Asked

Viewed 9,035 times

4

I did not find on the Internet a mask in the format BBB-1234 for car plates, the ones I found only validate when the field loses focus and even then only say if it is valid or invalid.

You’d need something that, in the first 3 characters, accepted letters, added the dash, and in the next 4 characters, only accepted numbers.

  • https://social.msdn.microsoft.com/Forums/pt-BR/01006330-99e0-4fe7-8ff4-8525969ec4b4/validao-placa-de-veculo-com-regex?forum=vscsharppt

4 answers

5


  • perfect... thank you

  • Firefox does not work. You have to make some adaptation?

2

The following code applies the standard mask to the South or Old, as user type:

var MercoSulMaskBehavior = function (val) {
    var myMask = 'SSS0A00';
    var mercosul = /([A-Za-z]{3}[0-9]{1}[A-Za-z]{1})/;
    var normal = /([A-Za-z]{3}[0-9]{2})/;
    var replaced = val.replace(/[^\w]/g, '');
    if (normal.exec(replaced)) {
        myMask = 'SSS-0000';
    } else if (mercosul.exec(replaced)) {
        myMask = 'SSS0A00';
    }
        return myMask;
    },

    mercoSulOptions = {
        onKeyPress: function(val, e, field, options) {
            field.mask(MercoSulMaskBehavior.apply({}, arguments), options);
        }
    };

    $(function() {
        $("body").delegate('input.placa','paste', function(e) {
            $(this).unmask();
        });
        $("body").delegate('input.placa','input', function(e) {
            $('input.placa').mask(MercoSulMaskBehavior, mercoSulOptions);
        });
    });

The delegate event causes you to define a parent element to find my selector, in case of content loading via ajax return. Each input in the key is called a "function" that validates the mask and defines whether it is Southern or Normal

2

  • Recognizes old standard(ABC-1234) and new standard from South Rail(ABC 1D23).
  • Converts to uppercase letters automatically.
  • Uses jquery.mask.js plugin.
$('input[name=plate]').mask('AAA 0U00', {
    translation: {
        'A': {
            pattern: /[A-Za-z]/
        },
        'U': {
            pattern: /[A-Za-z0-9]/
        },
    },
    onKeyPress: function (value, e, field, options) {
        // Convert to uppercase
        e.currentTarget.value = value.toUpperCase();

        // Get only valid characters
        let val = value.replace(/[^\w]/g, '');

        // Detect plate format
        let isNumeric = !isNaN(parseFloat(val[4])) && isFinite(val[4]);
        let mask = 'AAA 0U00';
        if(val.length > 4 && isNumeric) {
            mask = 'AAA-0000';
        }
        $(field).mask(mask, options);
    }
});

2

Complementing the @rray response, modify the mask to support the new board format:

$(document).ready(function(){
    $("#placa").inputmask({mask: ['AAA-9999','AAA9A99']});
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.