Forms 如何在Angular2中创建自定义验证器
我正在制作一个自定义验证器,用于检查输入是否为有效的电子邮件格式 这是我的验证器类:Forms 如何在Angular2中创建自定义验证器,forms,angular,custom-validators,Forms,Angular,Custom Validators,我正在制作一个自定义验证器,用于检查输入是否为有效的电子邮件格式 这是我的验证器类: import {FormControl} from "@angular/forms"; export class EmailValidator { static getEmailValidator() { return function emailValidator(control: FormControl): { [s: string]: boolean } {
import {FormControl} from "@angular/forms";
export class EmailValidator {
static getEmailValidator() {
return function emailValidator(control: FormControl): { [s: string]: boolean } {
if (!control.value.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/)) {
return {invalidChars: true};
}
}
}
}
我的HTML如下所示:
<div class="form-group">
<input class="form-control"
[(ngModel)]="model.email"
type="text"
id="name"
placeholder="Enter your email"
[formControl]="signupForm.controls['email']"
>
<div *ngIf="signupForm.controls['email'].errors?.required&& signupForm.controls['email'].touched"
class="alert alert-danger">Email is required</div>
<div *ngIf="signupForm.controls['email'].hasError('invalidChars') && signupForm.controls['email'].touched"
class="alert alert-danger">Please give a valid email address</div>
最后,我得到了一个例外:
Uncaught (in promise): Error: Error in ./SignupComponent class
SignupComponent - inline template:31:4 caused by: Cannot read property
'match' of undefined TypeError: Cannot read property 'match' of undefined at
emailValidator
我的问题是为什么我的匹配项是未定义的,以及如何实现自定义验证器最合适?由于验证器本身看起来很好,错误看起来很像您的
控件。值是未定义的,因为它是原始的。将emailValidator
功能更新为以下内容:
static getEmailValidator() {
return function emailValidator(control: FormControl): { [s: string]: boolean } {
if (control.value && !control.value.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/)) {
return {invalidChars: true};
}
}
因此,只有在提供了正则表达式的情况下,它才会尝试使用正则表达式测试值。由于验证器本身看起来很好,错误看起来很像您的控件。值未定义,因为它是原始的。将emailValidator
功能更新为以下内容:
static getEmailValidator() {
return function emailValidator(control: FormControl): { [s: string]: boolean } {
if (control.value && !control.value.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/)) {
return {invalidChars: true};
}
}
因此,只有在提供了正则表达式的情况下,它才会尝试使用正则表达式测试值。control.value未定义。我在加载页面时遇到了这个异常。另外,我还有一个关于将控件绑定到表单的问题。它不应该是formControlName=“email”
,并且[formGroup]=“signupForm”
在表单上(在本例中是在div
元素上)?但是关于验证器,不是简单的额外检查:if(control.value&!control.value.match(/^\w++[a-zA-Z+?\.[a-zA-Z]{2,3}$/){
是一个解决方案吗?这是问题,我没有考虑。我添加了(control.value&!control.value&!control.value.match(/^\w++[a-zA-Z]+.[a-zA-Z]{2,3$/),因此它首先检查它是否有值,当然,只要字段未被触及,就没有值。如果您使用解决方案编辑答案,我将接受它作为答案。control.value未定义。我在加载页面时遇到该异常。此外,我还有一个关于将控件绑定到表单的问题。它不应该是formControlName吗=“email”
,在表单上有[formGroup]=“signupForm”
(在本例中是在div
元素上)?但是关于验证器,不需要简单的额外检查:如果(control.value&!control.value.match(/^\w++[a-zA-Z+?\.[a-zA-Z]{2,3}$/){
是一个解决方案吗?这是问题所在,我没有想到。我添加了(control.value&!control.value.match(/^\w++[a-zA-Z++?\.[a-zA-Z]{2,3}$/),因此它首先检查它是否有值,当然,只要字段未被触及,就没有值。如果你用解决方案编辑你的答案,我会接受它作为答案。