[英]Angular form validation to validate the phone number
I am trying to validate the phone number using regex expression in angular我正在尝试使用 angular 中的正则表达式验证电话号码
HTML content 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 code TS代码
this.$form = this.$builder.group({
selectCountryCode: [null, Validators.required],
inputCountryCode: [null, [Validators.required, Validators.pattern("[0-9 ]{12}")]]
});
The validation pattern should allow numeric number with space because I am using the phone number masking which add space after 3 digits.验证模式应允许带空格的数字编号,因为我使用的是在 3 位数字后添加空格的电话号码掩码。
The pattern is not working keep getting phone numner validation false该模式不起作用,继续获取电话号码验证错误
Angular 4 Mobile number validation Angular 4 手机号码验证
Regex for field that allows numbers and spaces 允许数字和空格的字段的正则表达式
Masking directive屏蔽指令
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);
}
}
You can allow for:您可以允许:
Validators.pattern('[- +()0-9]+')
Your regex expression requires 12 symbols of [0-9 ]
, while you input contains only 11.您的正则表达式需要
[0-9 ]
12 个符号,而您输入的仅包含 11 个。
Update your regexp for inputCountryCode
to "[0-9 ]{11}"
:将
inputCountryCode
的正则表达式更新为"[0-9 ]{11}"
:
this.$form = this.$builder.group({
selectCountryCode: [null, Validators.required],
inputCountryCode: [null, [Validators.required, Validators.pattern("[0-9 ]{11}")]]
});
Or you can add a space after phone number in input, so it will be 12 symbols.或者您可以在输入的电话号码后添加一个空格,因此它将是 12 个符号。
But I would prefer to use more specific regexp for phone number like '[0-9]{3} [0-9]{3} [0-9]{3}'
, because with your pattern phone number 11 1111 111
or 111111
are valid numbers但我更愿意为电话号码使用更具体的正则表达式,例如
'[0-9]{3} [0-9]{3} [0-9]{3}'
,因为使用您的模式电话号码11 1111 111
或111111
是有效数字
Just another idea, similarly, you can actually force entered value to keep phone format, this is an example of US format 123-123-1234.另一个想法,类似地,您实际上可以强制输入值以保留电话格式,这是美国格式 123-123-1234 的示例。 First we limit users input on numbers only :
首先,我们限制用户只输入数字:
//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, "");
}
}
and then, we add phone field with directive phoneMask - in html :然后,我们在 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>
Here you filter numbers only (input)="numbersOnlyValidator($event)"
在这里你只过滤数字
(input)="numbersOnlyValidator($event)"
Here is Directive phoneMask used in html where you actually format input into dashed pattern NNN-NNN-NNNN :这是在 html 中使用的指令phoneMask ,您实际上将输入格式化为虚线模式 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('-');
}
}
DEMO stackblitz演示堆栈闪电战
You can use您可以使用
Validators.pattern("(09)[0-9 ]{9}")
example: 09112223333示例:09112223333
conditions: number must be start with '09', should be numerical and fixed length (in this sample 11 digit)条件:数字必须以'09'开头,应该是数字和固定长度(在此示例中为11位数字)
[- +()0-9]{10,12} // basic validation with limited to 10 to 12 numbers range
You can you one of these options你可以选择这些选项之一
With.ts file With.ts 文件
Validators.pattern('[- +()0-9]{10,12}')
With HTML file带有 HTML 文件
<input type="text" formControlName="MobileNumber" required pattern="[- +()0-9]{10,12}">
The issue was with问题是
Validators.pattern("[0-9 ]{12}")
Replace it with将其替换为
Validators.pattern(new RegExp("[0-9 ]{12}"))
Change code更改代码
this.$form = this.$builder.group({
selectCountryCode: [null, Validators.required],
inputCountryCode: [null, [Validators.required, Validators.pattern(new RegExp("[0-9 ]{12}"))]]
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.