我有一个文本框。用户可以在那里输入带+号的国家代码。如果他仅输入数字,我们不应允许他。他必须输入带有+号的国家代码,例如:+ 91,+ 230 ...我正在互联网上搜索正则表达式。我找不到关于angular 7的好的解决方案。请帮我解决这个问题。
代码:
ngOnInit() {
this.registerFormGroup = this.formBuilder.group({
clientId: ['', Validators.compose([Validators.required, Validators.pattern('^[0-9]*$')])],
mobileNumber: ['', Validators.compose([Validators.required, Validators.pattern('^[0-9]*$')])],
email: ['', Validators.compose([Validators.required, Validators.email, Validators.maxLength(1000)]) ],
countryCode: ['', Validators.compose([Validators.required, Validators.pattern('/^[- +()]*[0-9][- +()0-9]*$/')]), ],
});
}
答案 0 :(得分:2)
尝试以+
开头的正则表达式,并使其具有所需的位数
let regex = /^[+]\d{12}$/; // enter the total number if digits you want
let correct = '+911234567890'
let inCorrect = '911234567890'
console.log(regex.test(correct))
console.log(regex.test(inCorrect))
要在角度形式验证器中使用\d
,似乎我们必须转义“反斜杠”,因此您的模式将类似于:
Validators.pattern('^[+]\\d{12}$')
在此处查看示例:https://stackblitz.com/edit/angular-hdctcl?file=src/app/app.component.html
或者,您可以使用:
Validators.pattern('^[+][0-9]{12}$')
答案 1 :(得分:1)
您可以尝试这样
ngOnInit() {
const patternData = /^[+]\d{12}$/;
this.registerFormGroup = this.formBuilder.group({
clientId: ['', Validators.compose([Validators.required, Validators.pattern('^[0-9]*$')])],
mobileNumber: ['', Validators.compose([Validators.required, Validators.pattern('^[0-9]*$')])],
email: ['', Validators.compose([Validators.required, Validators.email, Validators.maxLength(1000)]) ],
countryCode: ['', Validators.compose([Validators.required, Validators.pattern(patternData)]), ],
});
}