![](/img/trans.png)
[英]Regex in JavaScript which allow maximum 10 digits, only one underscore in between the digits and prevent entering underscore after the first 5 digits
[英]javascript Regex to allow number and only one space after first three digits
我正在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();
}
}
公認這不是您所要求的純正則表達式解決方案,但是您的代碼示例表明這不是必需的:
// 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.