电话号码的自定义掩码

时间:2016-05-25 08:34:03

标签: javascript masking

我正在使用jsmask插件来屏蔽电话号码。 要求是

  1. 一开始可以选择+
  2. 它之间可以有空格
  3. 我试过这个     $('#Telephone').mask('+0000000 000 000 0000', { reverse: true }); 但它不接受可选加号。 是否有内置格式或我们可以为它自定义格式 请指教。

2 个答案:

答案 0 :(得分:0)

那是不可能的。

您只能在输入的末尾添加可选参数。

他们在Github有一个开放的拉取请求。

您可以查看here

答案 1 :(得分:0)

以下代码正常运行,您可以尝试一下。我已经为您创建了solution in JSfidller。如果你想要检查它。 的 HTML:

<form id="example-form" name="my-form">
    <label>Phone number:</label><br />
    <input id="phone-number" name="phone-number" type="text" maxlength="21" placeholder="+XXXXXXX XXX XXX XXXX" /><br /><br />
    <input type="button" value="Submit" />
</form>

<强>脚本:

    $('#phone-number', '#example-form')

        .keydown(function (e) {
            var key = e.charCode || e.keyCode || 0;
            $phone = $(this);

            // Adding blankspace in 9th, 13th and 17th position. 
//Change it according to your need
            if (key !== 8 && key !== 9) {
                if ($phone.val().length === 8) {
                    $phone.val($phone.val() + ' ');
                }
                if ($phone.val().length === 12) {
                    $phone.val($phone.val() + ' ');
                }           
                if ($phone.val().length === 16) {
                    $phone.val($phone.val() + ' ');
                }
            }

            // Allow numeric number and tab, backspace, delete keys only.
//Change it according to your need
            return (key == 8 || 
                    key == 9 ||
                    key == 46 ||
                    (key >= 48 && key <= 57) ||
                    (key >= 96 && key <= 105)); 
        })

        .bind('focus click', function () {
            $phone = $(this);

            if ($phone.val().length === 0) {
                $phone.val('+'); // as your phone number start with '+'
            }
            else {
                var val = $phone.val();
                $phone.val('').val(val); // Ensure cursor remains at the end
            }
        })

        .blur(function () {
            $phone = $(this);

            if ($phone.val() === '+') {
                $phone.val(''); // if somebody type '+' it will be vanish 
            }
        });