简体   繁体   中英

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:

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

OnkeyPress function code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM