Javascript 角度表单验证以验证电话号码

Javascript 角度表单验证以验证电话号码,javascript,angular,angular7,angular8,angular-validation,Javascript,Angular,Angular7,Angular8,Angular Validation,我试图在angular中使用正则表达式验证电话号码 HTML内容 <div class="form-group row"> <input type="text" class="form-control" appPhoneMask placeholder="Mobile Number" autocomplete="off" [ngClass]="{ 'is-invalid': (f.inputCountryC

我试图在angular中使用正则表达式验证电话号码

HTML内容

<div class="form-group row">
                <input type="text" class="form-control" appPhoneMask placeholder="Mobile Number" autocomplete="off"
                    [ngClass]="{ 'is-invalid': (f.inputCountryCode.errors && mobileNumberform.submitted) }"
                    formControlName="inputCountryCode">
                <div *ngIf="(f.inputCountryCode.invalid ) || (f.inputCountryCode.invalid && (f.inputCountryCode.dirty || f.inputCountryCode.touched))"
                    class="invalid-feedback">
                    <div *ngIf="f.inputCountryCode.errors.required">This field is required.</div>
                    <div *ngIf="f.inputCountryCode.errors.pattern">Invalid phone number.</div>
                </div>
            </div>
验证模式应该允许数字加空格,因为我使用的是电话号码屏蔽,它在3位数字后加空格

模式不起作用继续获取电话号码验证错误

掩蔽指令

export class PhoneMaskDirective {

  constructor(public ngControl: NgControl) { }

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event, false);
  }

  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event) {
    this.onInputChange(event.target.value, true);
  }


  onInputChange(event, backspace) {
    let newVal = event.replace(/\D/g, '');
    if (backspace && newVal.length <= 6) {
      newVal = newVal.substring(0, newVal.length - 1);
    }
    if (newVal.length === 0) {
      newVal = '';
    } else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '$1');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '$1 $2');
    } else if (newVal.length <= 9) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1 $2 $3');
    } else {
      newVal = newVal.substring(0, 10);
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1 $2 $3');
    }
    this.ngControl.valueAccessor.writeValue(newVal);
  }
}
导出类PhoneMaskDirective{
构造函数(公共ngControl:ngControl){}
@HostListener('ngModelChange',['$event']))
onModelChange(事件){
此.onInputChange(事件,false);
}
@HostListener('keydown.backspace',['$event']))
keydownBackspace(事件){
此.onInputChange(event.target.value,true);
}
onInputChange(事件,退格){
让newVal=event.replace(/\D/g');

if(backspace&&newVal.length您的正则表达式需要12个
[0-9]
符号,而您的输入只包含11个

inputCountryCode
的regexp更新为
“[0-9]{11}”

this.$form=this.$builder.group({
selectCountryCode:[null,Validators.required],
inputCountryCode:[null,[Validators.required,Validators.pattern(“[0-9]{11}”)]]
});
或者,您可以在输入中的电话号码后添加空格,这样它将是12个符号

但我更愿意对电话号码使用更具体的regexp,比如
'[0-9]{3}[0-9]{3}[0-9]{3}'
,因为您的模式电话号码
11111111

111111
是有效数字

问题在于

Validators.pattern(“[0-9]{12}”)

换成

Validators.pattern(new RegExp("[0-9 ]{12}"))
更改代码

this.$form = this.$builder.group({
      selectCountryCode: [null, Validators.required],
      inputCountryCode: [null, [Validators.required, Validators.pattern(new RegExp("[0-9 ]{12}"))]]
    });
你可以用

Validators.pattern("(09)[0-9 ]{9}")
示例:09112223333

条件: 数字必须以“09”开头,应为数字和固定长度(在此示例中为11位)

您可以考虑:

  • 9999999
  • +61 2 9999 9999
  • (02)9999999

另一个想法是,类似地,您可以强制输入值以保持电话格式,这是US格式123-123-1234的一个示例。首先,我们限制用户仅输入数字:

//Number formatting in your .ts file
  public numbersOnlyValidator(event: any) {
    const pattern = /^[0-9\-]*$/;
    if (!pattern.test(event.target.value)) {
      event.target.value = event.target.value.replace(/[^0-9\-]/g, "");
    }
  }
然后,我们在html中添加带有指示phoneMask的phone字段:

 <div class="form-group row">
           <input 
             type="text" 
             placeholder="phone number xxx-xxx-xxxx" 
             class="form-control" 
             id="phone" 
             name="phone" 
             maxlength="12"
            [(ngModel)]="phone" 
            phoneMask
            [ngClass]="{ 'is-invalid': phone.touched || form.submitted && phone.invalid }"
            #phone="ngModel" 
            phoneMask 
            (input)="numbersOnlyValidator($event)" />

            <div *ngIf="(phone.touched || form.submitted) &&
                phone.invalid" class="invalid-feedback">
                  <div *ngIf="phone.errors">
                    Please enter valid phone number.
                  </div>
                </div>
 </div>

演示

您使用的是被动表单吗?是的,我使用的是被动表单Regex尝试匹配继续标记的12个字符[0-9],但您只输入了11个字符,因此它会给出errortry Yes,这是我正在使用的同一个字符,但我已删除了括号和连字符,并尝试进行电话号码验证,但该操作不起作用。我已添加了屏蔽代码。您可以让我知道我在哪里犯了错误吗?您刚刚共享了示例代码。因此,该指令是正确的。Make sur如果您在html中正确使用它,请检查您的表单字段在html中的命名以及您如何填写formI也更新了html内容,html内容与表单名称和控件配合良好。还有其他问题,我无法解决。谢谢!Validators.pattern(“[-+()0-9]{6,}”)如果您希望至少有6个字符。
//Number formatting in your .ts file
  public numbersOnlyValidator(event: any) {
    const pattern = /^[0-9\-]*$/;
    if (!pattern.test(event.target.value)) {
      event.target.value = event.target.value.replace(/[^0-9\-]/g, "");
    }
  }
 <div class="form-group row">
           <input 
             type="text" 
             placeholder="phone number xxx-xxx-xxxx" 
             class="form-control" 
             id="phone" 
             name="phone" 
             maxlength="12"
            [(ngModel)]="phone" 
            phoneMask
            [ngClass]="{ 'is-invalid': phone.touched || form.submitted && phone.invalid }"
            #phone="ngModel" 
            phoneMask 
            (input)="numbersOnlyValidator($event)" />

            <div *ngIf="(phone.touched || form.submitted) &&
                phone.invalid" class="invalid-feedback">
                  <div *ngIf="phone.errors">
                    Please enter valid phone number.
                  </div>
                </div>
 </div>
import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[phoneMask]'
})
export class PhoneMasksDirective {

  constructor() { }

  @HostListener('input', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    const input = event.target as HTMLInputElement;
    let trimmed = input.value.replace(/\s+/g, '');

    if (trimmed.length > 12) {
      trimmed = trimmed.substr(0, 12);
    }
 
    trimmed = trimmed.replace(/-/g,'');

    let numbers = [];
    numbers.push(trimmed.substr(0,3));
    if(trimmed.substr(3,3)!=="")
    numbers.push(trimmed.substr(3,3));
    if(trimmed.substr(6,4)!="")
    numbers.push(trimmed.substr(6,4));
    input.value = numbers.join('-');

  }

}