Kar*_*rty -1 angular angular-reactive-forms
这就是我验证密码、确认密码和电子邮件、确认电子邮件的方式。如您所见,我有一个函数 fieldMatcher,它被调用来检查电子邮件和密码验证。
// Works
createForm() {
this.formGroup = this._formBuilder.group({
firstName: '',
lastName: '',
email: '',
confirmEmail: '',
password: '',
confirmPassword: '',
}, {validator: this.fieldMatcher});
}
fieldMatcher(c: AbstractControl): { invalid: boolean } {
if (c.get('password').value !== c.get('confirm').value) {
return {invalid: true};
}
if (c.get('email').value !== c.get('confirmEmail').value) {
return {invalid: true};
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想将控件作为参数传递给 fieldMatcher 函数,以便我减少如下代码但不起作用,
// Do not Work
createForm() {
this.formGroup = this._formBuilder.group({
firstName: '',
lastName: '',
email: '',
confirmEmail: '',
password: '',
confirmPassword: '',
},{validator: this.fieldMatcher(value1, value2)});
}
fieldMatcher(c: AbstractControl, value1, value2): { invalid: boolean } {
if (c.get(value1).value !== c.get(value2).value) {
return {invalid: true};
}
}
Run Code Online (Sandbox Code Playgroud)
那是因为您的value1和value2根本不对应任何。您需要发送密钥而不是value1和value2。从下面的例子中获取参考。
工作Plunker: http ://plnkr.co/edit/RlWslfyr1eiTq4MSc3iY?p=preview
import {Component, FormBuilder, Control, ControlGroup, Validators} from 'angular2/angular2'
@Component({
selector: 'my-app',
template: `
<form [ng-form-model]="form">
<label for="name">Name:</label>
<input id="name" type="text" ng-control="name">
<br>
<div ng-control-group="matchingEmail">
<label for="email">Email:</label>
<input id="email" type="email" ng-control="email">
<br>
<label for="confirmEmail">Confirm Email:</label>
<input id="confirmEmail" type="email" ng-control="confirmEmail">
</div>
<br>
<div ng-control-group="matchingPassword">
<label for="password">Password:</label>
<input id="password" type="password" ng-control="password">
<br>
<label for="confirmPassword">Confirm Password:</label>
<input id="confirmPassword" type="password" ng-control="confirmPassword">
</div>
</form>
<p>Valid?: {{form.valid}}</p>
<pre>{{form.value | json}}</pre>
`
})
export class App {
form: ControlGroup
constructor(fb: FormBuilder) {
this.form = fb.group({
name: [''],
matchingEmail: fb.group({
email: ['', Validators.required],
confirmEmail: ['', Validators.required]
}, {validator: this.fieldMatcher('email','confirmEmail')}),
matchingPassword: fb.group({
password: ['', Validators.required],
confirmPassword: ['', Validators.required]
}, {validator: this.fieldMatcher('password','confirmPassword')})
});
}
fieldMatcher(value1: string, value2: string) {
return (group: ControlGroup) => {
if (group.controls[value1].value !== group.controls[value2].value) {
return group.controls[value2].setErrors({notEquivalent: true})
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10269 次 |
| 最近记录: |