javascript正则表达式允许数字,前三位数后只有一个空格

时间:2018-02-14 12:12:28

标签: javascript regex angular ionic-framework

我正在开发Angular \ Ionic 3项目,我想要一个正则表达式来验证输入框中输入的电话号码。目前我可以限制用户只输入数字,但我想要3个数字,然后一个空间然后7位数...... 例如)300 1234567 以下是我的HTML代码:

<ion-input type="tel" 
                  (input)="onKeyPress($event,MobileNoDisplay)" 
                   maxlength="11" 
                   placeholder="300 1122345" 
                   [value]="MobileNoDisplay"
                   [(ngModel)]="MobileNoDisplay">
        </ion-input>

OnkeyPress功能代码:

onKeyPress(event,val: string) {

    if (/[\D]/.test(val) ) { 
    this.MobileNoDisplay = val.replace(/[\D]+/g, '');//this will remove any non-
                                                     numerical value
     console.log("MobileNoDisplay-->" + this.MobileNoDisplay);
    }
    else{
      console.log("ELSE CHECK");      
    }

    event.stopPropagation();
  }

}

1 个答案:

答案 0 :(得分:0)

这无疑是您要求的纯正regexp解决方案,但您的代码示例表明它没有必要:

// first check if the value does not match the pattern (see the exclamation mark)
if (!/^\d{3} \d{7}$/.test(val)) { 
    // first remove non-digits
    var numeric = val.replace(/\D/g, '');
    // get the first 3 chars, and if the filtered number is longer then 3, add a space, then add the remaining 7 chars, beginning on the fourth char (index 3)
    this.MobileNoDisplay = numeric.substr(0, 3)
        + (numeric.length > 3 ? ' ' + numeric.substr(3, 7) : '');
    console.log("MobileNoDisplay-->" + this.MobileNoDisplay);
}