Angular表单验证:验证电话号码

12
我正在尝试在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>

TS代码

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

验证模式应该允许带有空格的数字,因为我正在使用电话号码掩码,它会在3个数字后添加空格。

enter image description here

这个模式不起作用,一直得到电话号码验证错误的结果。

Angular 4 手机号码验证

允许数字和空格的字段正则表达式

掩码指令

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

你正在使用响应式表单吗? - Rijo
1
正则表达式尝试匹配前面的 [0-9 ] 令牌的12个字符,但您只输入了11个字符,因此会报错。 - Ininiv
请尝试使用 https://stackblitz.com/edit/angular6-phone-mask。 - dasunse
是的,那就是我正在使用的那个,但我已经去掉了括号和连字符,尝试进行电话号码验证。 - San Jaisy
@Ininiv 我在输入文本框中输入了12个字符,但仍然出现错误。 - San Jaisy
显示剩余2条评论
8个回答

22

您可以允许:

  • 9999 9999
  • +61 2 9999 9999
  • (02) 9999 9999
Validators.pattern('[- +()0-9]+')

7
谢谢!如果您希望至少有6个字符,则可以使用Validators.pattern('[- +()0-9]{6,}')。 - Daniel Jankowski

9

你的正则表达式需要[0-9 ]这12个符号,但是你输入的只有11个。

请更新inputCountryCode的正则表达式为"[0-9 ]{11}"

 this.$form = this.$builder.group({
      selectCountryCode: [null, Validators.required],
      inputCountryCode: [null, [Validators.required, Validators.pattern("[0-9 ]{11}")]]
    });

或者你可以在输入框中电话号码后面添加一个空格,这样它就会成为12个字符。

但是我更喜欢使用更具体的电话号码正则表达式,例如'[0-9]{3} [0-9]{3} [0-9]{3}',因为使用你的模式,电话号码11 1111 111111111 都是有效的数字。


1
那个不起作用。我已经添加了掩码代码,你能告诉我哪里出错了吗? - San Jaisy
你刚刚分享了来自这里的示例代码。所以指令是正确的。确保在HTML中正确使用它,还要检查HTML中表单字段的命名以及如何填写表单。 - Anna
我已经更新了HTML内容,表单名称和控件都没问题。还有其他的问题,我无法找出原因。 - San Jaisy

1

另一个想法是,同样地,您实际上可以强制输入的值保持电话格式,这是美国格式的示例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, "");
    }
  }

然后,我们使用指令phoneMask在html中添加电话字段:
 <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>

在这里,你只过滤数字(input)="numbersOnlyValidator($event)"

这是指令phoneMask,用于在html中将输入格式化为带有破折号的模式NNN-NNN-NNNN:

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('-');

  }

}

演示 stackblitz


1
[- +()0-9]{10,12} // basic validation with limited to 10 to 12 numbers range

你可以使用以下其中一种选项

使用 .ts 文件

Validators.pattern('[- +()0-9]{10,12}')

使用HTML文件

<input type="text" formControlName="MobileNumber" required pattern="[- +()0-9]{10,12}">

0

您可以使用

Validators.pattern("(09)[0-9 ]{9}")

示例:09112223333

条件: 号码必须以'09'开头,应为数字且长度固定(在此示例中为11位)


0

我使用“phone”库。

npm install phone

要导入:

import { phone } from 'phone';

使用方法:

let a = phone('(817) 569-8900', {country: 'USA'});
console.log(a)

这将会得到如下结果:

{isValid: true, phoneNumber: '+18175698900', countryIso2: 'US', countryIso3: 'USA', countryCode: '+1'}

0

您可以使用

Validators.pattern('^(?!0+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$')

在当前的写法下,你的回答不清楚。请编辑以添加额外的细节,帮助其他人理解这如何回答所提出的问题。你可以在帮助中心找到更多关于如何撰写好的回答的信息。 - Community

-1
问题出在于

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

这对我有用,通过添加新的RegExp函数,我修改了这个答案以适应我的电子邮件或电话问题 Validators.pattern(new RegExp("([0-9 ]{11})|([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3})")) - akisoft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接