首页 文章

电话号码的自定义掩码

提问于
浏览
1

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

  • 它可以在开始时有可选项

  • 它们之间可以有空格

我试过这个 $('#Telephone').mask('+0000000 000 000 0000', { reverse: true }); 但它不接受可选加号 . 是否有内置格式或我们可以有自定义格式请告知 .

2 回答

  • 0

    这不可能 .

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

    他们在Github有一个开放式拉请求 .

    你可以查一下here .

  • 0

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

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

    <input type="button" value="Submit" /> </form>

    Script:

    $('#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 
                }
            });
    

相关问题