[英]javascript Regex to allow number and only one space after first three digits
I am working on Angular\\Ionic 3 project and I want a regex to validate the phone number that is enter in the Input box.Currently I am able restrict the user to enter only the number but I want 3 digits and then one space and then 7 digits... eg) 300 1234567 Below is my HTML code: 我正在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 function code: 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();
}
} }
This is admittedly not a pure-regexp solution you asked for but your code sample suggests it's not necessary: 公认这不是您所要求的纯正则表达式解决方案,但是您的代码示例表明这不是必需的:
// 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.