【问题标题】:javascript Regex to allow number and only one space after first three digitsjavascript正则表达式允许数字和前三位数字后只有一个空格
【发布时间】:2018-07-25 00:18:03
【问题描述】:

我正在处理 Angular\Ionic 3 项目,我想要一个正则表达式来验证在输入框中输入的电话号码。目前我可以限制用户只输入号码,但我想要 3 位数字,然后是 1空格,然后是 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();
  }

}

【问题讨论】:

  • 可以添加属性模式吗?喜欢pattern="\d{3}\s\d{7}"
  • /^\d{3} \d{7}$/.test(val)
  • 不,它实际上不起作用,它实际上在 3 位数字后用空白空间替换整个事物......我想在运行时删除任何非数字值,并且在前三个数字之后只允许一个空格数字。
  • 我尝试了 \d{3}\s\d{7} 和 /^\d{3} \d{7}$/ 但它们也没有工作...请检查我的代码是否在 val.replace 处正确替换了 val??我的 val.replace 可以与 /[\D]+/g 一起正常工作..但似乎不适用于 \d{3}\s\d{7} 和/^\d{3} \d{7}$/..
  • 也许this.MobileNoDisplay = val.match(/\d{3}\s\d{7}/)[0]

标签: javascript regex angular ionic-framework


【解决方案1】:

诚然,这不是您要求的纯正则表达式解决方案,但您的代码示例表明没有必要:

// 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);
}

【讨论】:

  • 当我在空框中输入数字时,它运行良好,但是当我删除数字时,它会卡在空格字符处,并且不允许我删除空格并重新输入又号??
  • @j.doe 公平点,添加了一个条件来检查过滤后的数字是否足够长以添加空格。
猜你喜欢
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 2021-10-08
  • 2022-01-14
  • 2016-08-22
  • 1970-01-01
  • 2018-11-05
相关资源
最近更新 更多