检查电子邮件是否匹配模糊
check if emails match on blur
我正在尝试检查电子邮件字段和确认电子邮件字段是否相互匹配。也就是说,用户输入他们的电子邮件,然后他们必须再次确认。我希望 match/validation 在模糊时发生(当用户按下回车键或文本字段失去焦点时)。
这是我的 ts 文件:
import {Component, OnInit} from '@angular/core';
import {User} from './user.interface';
import {FormBuilder, FormGroup, ValidatorFn} from '@angular/forms';
@Component({
selector: 'my-email',
templateUrl: '/app/components/profile/email.component.html',
styleUrls:['styles.css'],
})
export class EmailComponent implements OnInit {
public user : User;
Form : FormGroup;
ngOnInit() {
// initialize model here
this.user = {
Email: '',
confirmEmail: ''
}
if(this.Form.valid) {
this.displayErrors = false;
}
}
constructor(fb: FormBuilder, private cookieService: CookieService, private router: Router) {
this.Form = fb.group({
email: [''],
confirmEmail: ['']
},
{
validator: this.matchingEmailsValidator('email', 'confirmEmail')
});
}
save(model: User, isValid: boolean) {
// call API to save customer
//save email
}
matchingEmailsValidator(emailKey: string, confirmEmailKey: string): ValidatorFn {
return (group: FormGroup): {[key: string]: any} => {
let email = group.controls[emailKey];
let confirmEmail = group.controls[confirmEmailKey];
if (email.value !== confirmEmail.value) {
return {
mismatch: true
};
}
};
}
}
这是我的观点:
<form [formGroup]="Form" novalidate (ngSubmit)="Form.valid && save(Form.value, Form.valid)">
<div class="container-fluid">
<div id = "container" class="contain" style="text-align: center">
<div>
<fieldset class="form-group">
<label id = "rounded" class="item item-input .col-md-6 .col-md-offset-3">
<input class="email-address-entry form-control" name="email" type="email" placeholder="name@domain.com" formControlName="email" pattern="^(\w|[0-9.!#$%&’*+/=?^_\`{|}~-])+@(\w|[0-9-])+(?:[.](\w|[0-9-])+)*$"/>
</label>
<p class="Reenter-your-email">Reenter your email to confirm</p>
<label id = "rounded" class="item item-input">
<input class="email-address-entry form-control" (blur)="displayErrors=true" name="confirmEmail" type="email" placeholder="name@domain.com" formControlName="confirmEmail" validateEqual="email"/>
</label>
</fieldset>
</div>
<div>
<label class="entry-invalid">
<p *ngIf="displayErrors && !Form.get('email').valid">The email you entered does not match.</p>
</label>
</div>
<div (click)="Form.get('email').length > 0 ? save(Form.value, Form.valid) : NaN" class="{{ Form.get('email').length > 0 ? 'container-fluid anchorBottomHighlight' : 'container-fluid anchorBottom'}}">
<label class="footerLabel">Confirm</label>
</div>
</div>
</div>
</form>
目前,根据其设置方式,会进行验证,但在输入正确的匹配项时不会清除验证。我想知道如何正确设置我的视图?因此,当设置正确匹配时验证消息为 shown/hidden 而不是。
而且 Form.get('email').length > 0
似乎永远不会大于 0/永远不会命中,所以我的标签不会切换为可点击。
我正在使用 Angular 2 和反应形式。
您似乎混合了两种形式语法:template-driven 形式 和 model-driven 形式 .
由于您在 class 中使用 FormBuilder
声明了一个表单模型,我假设您想要一个 model-driven 表单 .
这意味着您的字段不需要 [(ngModel)]
或 #EmailAddress
.
等属性
而不是:
<input type="email" [(ngModel)]="user.EmailAddress" required #EmailAddress="ngModel">
这样写:
<!-- Now I'm using `formControlName` to bind the field to the model -->
<!-- Its value must match one of the names you used in the FormBuilder -->
<input type="email" formControlName="email">
您的所有验证器都必须在 FormBuilder 中声明。不只是 matchingEmailsValidator
,还有 required
:
this.Form = fb.group({
email: ['', Validators.required],
confirmEmail: ['', Validators.required]
},
{
validator: this.matchingEmailsValidator('email', 'confirmEmail')
});
现在您可以使用以下语法访问字段:
// In the class
this.Form.get('email').value
this.Form.get('email').errors
<!-- In the template -->
{{ Form.get('email').value }}
{{ Form.get('email').errors }}
您可以使用这些语法来显示错误。例如:
<input type="email" formControlName="email">
<p *ngIf="Form.get('email').dirty && Form.get('email').errors.required">
This field is required.
</p>
在上面的示例中,如果触摸了 email
字段(即用户尝试输入内容)并且存在 required
错误,我将显示一条错误消息。
您还可以通过使用浏览器的开发工具检查表单的标记来验证您的验证规则是否得到执行。 Angular 应该已将 class 之类的 .ng-invalid
或 .ng-valid
添加到具有验证规则的 <input>
标签中。
最后,关于检查电子邮件匹配的问题 模糊。您不能推迟 Angular 的验证,它会在 real-time 中发生(当用户键入时)。但是您可以等待模糊事件显示错误。
将最后一条建议与我之前的示例结合起来,如果电子邮件字段为空并且失去焦点(模糊事件),您应该如何处理错误:
<input type="email" formControlName="email" (blur)="displayErrors=true">
<p *ngIf="displayErrors && Form.get('email').dirty && Form.get('email').errors.required">
This field is required.
</p>
更新(2017 年 2 月 1 日)在 Euridice 发布后 this Plunkr:
- 您的模板中还有很多验证代码。就像我说的,所有验证器都应该在表单模型中声明(使用
FormBuilder
)。进一步来说:
email
字段中的 pattern="..."
属性应替换为表单模型中的 Validators.pattern()
。
confirmEmail
字段中的 validateEqual="email"
属性是什么?你没有在任何地方使用它。
- 主要问题是你的测试显示错误信息:
*ngIf="displayErrors && !Form.get('email').valid && Form.get('email').error.mismatch"
。
- 首先,属性 是
errors
加上 "s",而不是 error
。
- 此外,您的自定义验证器在表单本身上设置了错误,而不是在电子邮件字段上。这意味着您应该从
Form.errors.mismatch
检索 mismatch
自定义错误,而不是 Form.get('email').errors.mismatch
.
这是更新后的工作 Plunkr:https://plnkr.co/edit/dTjcqlm6rZQxA7E0yZLa?p=preview
我正在尝试检查电子邮件字段和确认电子邮件字段是否相互匹配。也就是说,用户输入他们的电子邮件,然后他们必须再次确认。我希望 match/validation 在模糊时发生(当用户按下回车键或文本字段失去焦点时)。
这是我的 ts 文件:
import {Component, OnInit} from '@angular/core';
import {User} from './user.interface';
import {FormBuilder, FormGroup, ValidatorFn} from '@angular/forms';
@Component({
selector: 'my-email',
templateUrl: '/app/components/profile/email.component.html',
styleUrls:['styles.css'],
})
export class EmailComponent implements OnInit {
public user : User;
Form : FormGroup;
ngOnInit() {
// initialize model here
this.user = {
Email: '',
confirmEmail: ''
}
if(this.Form.valid) {
this.displayErrors = false;
}
}
constructor(fb: FormBuilder, private cookieService: CookieService, private router: Router) {
this.Form = fb.group({
email: [''],
confirmEmail: ['']
},
{
validator: this.matchingEmailsValidator('email', 'confirmEmail')
});
}
save(model: User, isValid: boolean) {
// call API to save customer
//save email
}
matchingEmailsValidator(emailKey: string, confirmEmailKey: string): ValidatorFn {
return (group: FormGroup): {[key: string]: any} => {
let email = group.controls[emailKey];
let confirmEmail = group.controls[confirmEmailKey];
if (email.value !== confirmEmail.value) {
return {
mismatch: true
};
}
};
}
}
这是我的观点:
<form [formGroup]="Form" novalidate (ngSubmit)="Form.valid && save(Form.value, Form.valid)">
<div class="container-fluid">
<div id = "container" class="contain" style="text-align: center">
<div>
<fieldset class="form-group">
<label id = "rounded" class="item item-input .col-md-6 .col-md-offset-3">
<input class="email-address-entry form-control" name="email" type="email" placeholder="name@domain.com" formControlName="email" pattern="^(\w|[0-9.!#$%&’*+/=?^_\`{|}~-])+@(\w|[0-9-])+(?:[.](\w|[0-9-])+)*$"/>
</label>
<p class="Reenter-your-email">Reenter your email to confirm</p>
<label id = "rounded" class="item item-input">
<input class="email-address-entry form-control" (blur)="displayErrors=true" name="confirmEmail" type="email" placeholder="name@domain.com" formControlName="confirmEmail" validateEqual="email"/>
</label>
</fieldset>
</div>
<div>
<label class="entry-invalid">
<p *ngIf="displayErrors && !Form.get('email').valid">The email you entered does not match.</p>
</label>
</div>
<div (click)="Form.get('email').length > 0 ? save(Form.value, Form.valid) : NaN" class="{{ Form.get('email').length > 0 ? 'container-fluid anchorBottomHighlight' : 'container-fluid anchorBottom'}}">
<label class="footerLabel">Confirm</label>
</div>
</div>
</div>
</form>
目前,根据其设置方式,会进行验证,但在输入正确的匹配项时不会清除验证。我想知道如何正确设置我的视图?因此,当设置正确匹配时验证消息为 shown/hidden 而不是。
而且 Form.get('email').length > 0
似乎永远不会大于 0/永远不会命中,所以我的标签不会切换为可点击。
我正在使用 Angular 2 和反应形式。
您似乎混合了两种形式语法:template-driven 形式 和 model-driven 形式 .
由于您在 class 中使用 FormBuilder
声明了一个表单模型,我假设您想要一个 model-driven 表单 .
这意味着您的字段不需要 [(ngModel)]
或 #EmailAddress
.
而不是:
<input type="email" [(ngModel)]="user.EmailAddress" required #EmailAddress="ngModel">
这样写:
<!-- Now I'm using `formControlName` to bind the field to the model -->
<!-- Its value must match one of the names you used in the FormBuilder -->
<input type="email" formControlName="email">
您的所有验证器都必须在 FormBuilder 中声明。不只是 matchingEmailsValidator
,还有 required
:
this.Form = fb.group({
email: ['', Validators.required],
confirmEmail: ['', Validators.required]
},
{
validator: this.matchingEmailsValidator('email', 'confirmEmail')
});
现在您可以使用以下语法访问字段:
// In the class
this.Form.get('email').value
this.Form.get('email').errors
<!-- In the template -->
{{ Form.get('email').value }}
{{ Form.get('email').errors }}
您可以使用这些语法来显示错误。例如:
<input type="email" formControlName="email">
<p *ngIf="Form.get('email').dirty && Form.get('email').errors.required">
This field is required.
</p>
在上面的示例中,如果触摸了 email
字段(即用户尝试输入内容)并且存在 required
错误,我将显示一条错误消息。
您还可以通过使用浏览器的开发工具检查表单的标记来验证您的验证规则是否得到执行。 Angular 应该已将 class 之类的 .ng-invalid
或 .ng-valid
添加到具有验证规则的 <input>
标签中。
最后,关于检查电子邮件匹配的问题 模糊。您不能推迟 Angular 的验证,它会在 real-time 中发生(当用户键入时)。但是您可以等待模糊事件显示错误。
将最后一条建议与我之前的示例结合起来,如果电子邮件字段为空并且失去焦点(模糊事件),您应该如何处理错误:
<input type="email" formControlName="email" (blur)="displayErrors=true">
<p *ngIf="displayErrors && Form.get('email').dirty && Form.get('email').errors.required">
This field is required.
</p>
更新(2017 年 2 月 1 日)在 Euridice 发布后 this Plunkr:
- 您的模板中还有很多验证代码。就像我说的,所有验证器都应该在表单模型中声明(使用
FormBuilder
)。进一步来说:email
字段中的pattern="..."
属性应替换为表单模型中的Validators.pattern()
。confirmEmail
字段中的validateEqual="email"
属性是什么?你没有在任何地方使用它。
- 主要问题是你的测试显示错误信息:
*ngIf="displayErrors && !Form.get('email').valid && Form.get('email').error.mismatch"
。- 首先,属性 是
errors
加上 "s",而不是error
。 - 此外,您的自定义验证器在表单本身上设置了错误,而不是在电子邮件字段上。这意味着您应该从
Form.errors.mismatch
检索mismatch
自定义错误,而不是Form.get('email').errors.mismatch
.
- 首先,属性 是
这是更新后的工作 Plunkr:https://plnkr.co/edit/dTjcqlm6rZQxA7E0yZLa?p=preview