Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mask an HTML input using javascript?

Tags:

javascript

How can I mask a US phone using javascript on an HTML control.

I would like the input to force the text to be in the following format:

[(111)111-1111]

Here is what I have currently:

mask(str, textbox, loc, delim) {
    var locs = loc.split(',');
    for (var i = 0; i <= locs.length; i++) {
        for (var k = 0; k <= str.length; k++)
        {
            if (k == locs[i]) {
                if (str.substring(k, k + 1) != delim) {
                    str = str.substring(0,k) + delim + str.substring(k,str.length)
                }
             }
         }
     }
     textbox.value = str
} 
like image 587
Ramasani Indrashaker Avatar asked Oct 05 '11 18:10

Ramasani Indrashaker


1 Answers

There are three common ways for handling phone number input of a guaranteed format:

1. Accept all numerical input anyway

The likelihood of users with obscure numbers but still living in the US is higher than ever. Accepting all kinds of numerical input alleviates the concern as the number will only be useless if they gave you either not enough numbers or the wrong ones.

2. Split it into three text boxes of fixed lengths

A lot of financial software does this. Not sure why, specifically, but it seems to be rather frequent there. A recommendation is to advance the cursor after keypress to the next box if they've typed the max limit on the textboxes. Also, this guarantees you will get the numbers in whatever format you're expecting, because you can just append the resulting post variables together.

Example of the HTML:

<input id="phonePart1" maxlength="3" name="phonePart1"/>
<input id="phonePart2" maxlength="3" name="phonePart2"/>
<input id="phonePart3" maxlength="4" name="phonePart3"/>

and a little jQuery snippet to merge the three in your format:

var phonePart1 = parseInt($("#phonePart1").val(), 10);
var phonePart2 = parseInt($("#phonePart2").val(), 10);
var phonePart3 = parseInt($("#phonePart3").val(), 10);
var phone = "(";

if (isNaN(phonePart1)||isNaN(phonePart2)||isNan(phonePart3)) {

    // Incorrect format

} else { 

    phone = phone + phonePart1 + ")" + phonePart2 + "-" + phonePart3;

}

3. Use a regular expression to match the number format

You can use a combination of regular expressions to match multiple numbers, or explicitly the one you are asking about. This is probably the technique you're looking for. This is the regular expression:

/\([0-9]{3}\)[0-9]{3}-[0-9]{4}/

You'd use it like this:

if (yourphonevariable.match(/\([0-9]{3}\)[0-9]{3}-[0-9]{4}/))
{
    // it's valid
}

4. If you're looking to format the text itself with a mask...

Consider the jQuery plugin at http://digitalbush.com/projects/masked-input-plugin/. User @John Gietzen suggested this to me outside of this post, so feel free to give him kudos for it.

like image 169
CassOnMars Avatar answered Sep 21 '22 02:09

CassOnMars