如何使用HTML模式的JQuery InputMask

时间:2017-05-05 13:58:32

标签: javascript jquery html regex input-mask

我有电话号码的HTML输入框。

我在输入时使用InputMask格式化后续860000000中的输入8 600 00 000

$(window).load(function()
{
   var phones = [{ "mask": "# ### ## ###"}, { "mask": "# ### ## ###"}];
    $('#phone').inputmask({ 
        mask: phones, 
        greedy: false, 
        definitions: { '#': { validator: "[0-9]", cardinality: 1}} });
});

我也在使用HTML模式来检查数字是否以86开头并且总共有9位数,但是InputMask它停止了工作,并且无法以任何方式实现它:< / p>

<label for="phone" class="first-col">Mobile No.:</label>
<input type="text" id="phone" placeholder="8 600 00 000" required pattern="(86)\d{7}" />

如果有效,则添加绿色边框的CSS:

input:required:valid {
    box-shadow: 0 0 5px #5cd053;
    border-color: #28921f;
}

你有什么想法吗?

JS Fiddle

1 个答案:

答案 0 :(得分:0)

您必须使用keyup事件和regex,如下所示 无需使用库

&#13;
&#13;
document.getElementById("phone").addEventListener("keyup", function(){
    // restart the match
    this.value = this.value.replace(/\s/g, "");
    // Assess the amount needed
    var v = this.value.match(/(\d)(\d{1,3})?(\d{1,2})?(\d+)?/);
    if(v){
      // Save the desired value depending on its existence
      v =  (v[1]?v[1]+(v[2]?" "+v[2]+(v[3]?" "+v[3]+(v[4]?" "+v[4]:""):""):""):"");
      // and yea!
      this.value = v;
    }
});
&#13;
<input  type="text" id="phone" placeholder="8 600 00 000" required onkeypress='return event.charCode >= 48 && event.charCode <= 57 && this.value.length < 12' pattern="\b86" title="description" value="8 6"/>
&#13;
&#13;
&#13;