Nikk
Nikk

Reputation: 7889

jQuery phone number masking with Regex not working

I've been trying to mask the phone number into a region specific format.

$("input:text[name=phone_number]").keyup(function() {
    var number = $(this).val().replace(/[^\d]/g, '');

        number = number.replace(/(\d{3})(\d{3})(\d{3})/, "($1) $2-$3");

        $(this).val(number);
});

The problem I am having with the script above is that regex is waiting for 3 numbers before it replaces the value in the input field.

And additionally I have to press enter for the effects to take place.


Is there a way I can make (\d{3}) this more dynamic. For example even if I've entered only 1 digit it should still display (0 ).

And then I continue entering (05 )... and so on...to a format that looks like this (051) 000-000?

I don't want to use additional plugins. I know there are many out there.

Upvotes: 1

Views: 1077

Answers (2)

kip
kip

Reputation: 1140

I made a simple mask, check:

$("input[name=phone_number]").keydown(function(e) {
    var actualValue = e.key;
    var baseMask = '(###) ###-###';
    var valueInput = this.value.match(/\d/g);
    if (actualValue !== 'Backspace' && /[^\d]/.test(actualValue)) {
        return false;
    }
    if (actualValue === 'Backspace') {
        if (!valueInput) {
            return false;
        }
        valueInput.pop();
        actualValue = '#';
    }
    var numsValues = valueInput ? valueInput.concat(actualValue) : [actualValue];
    $.each(numsValues, function() {
        baseMask = baseMask.replace(/\#/, this);
    });
    $(this).val(baseMask);
    return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="phone_number">

Upvotes: 2

Laassari
Laassari

Reputation: 326

$("#input").keyup(function() {
    var number = $(this).val().replace(/[^\d]/g, "");

    number = number.replace(/(\d{3})(\d{0,3})(\d{0,3})/, function(match, p1, p2, p3) {
        if (p2.length < 1)
            return "(" + p1 + ") ";
        else if (p3.length < 1)
            return "(" + p1 + ") " + p2;
        return "(" + p1 + ") " + p2 + "-" + p3;
    });

    $(this).val(number);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id=input placeholder="type your number">

Upvotes: 0

Related Questions