[英]Angular2 Form validation
Goal is to compare two password field to check whether they are identical: 目标是比较两个密码字段以检查它们是否相同:
<form [ngFormModel]="myForm" (ngSubmit)="onSubmit(myForm.value)">
<ion-label floating>password</ion-label>
<ion-input type="password" [ngFormControl]="password1" id="password1"></ion-input>
<ion-label floating>Repeat password</ion-label>
<ion-input type="password" [ngFormControl]="password2" id="password2"></ion-input>
<div *ngIf="!myForm.valid">
<p *ngIf="myForm.errors.areEqual">
The two passwords do not match
</p>
</div>
<button type="submit" [disabled]="!myForm.valid">Next</button>
</form>
The class is setup as below: 该类的设置如下:
export class SignupPage3 {
myForm: ControlGroup;
password1: AbstractControl;
password2: AbstractControl;
constructor(public nav: NavController, fb: FormBuilder,private signupData: SignupDataService) {
this.myForm = fb.group({
'password1': ['', Validators.required],
'password2': ['', Validators.required]
}, {validator: this.areEqual});
this.password1 = this.myForm.controls['password1'];
this.password2 = this.myForm.controls['password2'];
}
areEqual(group: ControlGroup) {
let password1 = group.controls.password1;
let password2 = group.controls.password2;
if (password1.value === password2.value) {
return null;
} else {
return { "areEqual": true};
}
}
}
When the class is loaded i get this error: 当类被加载时,我得到这个错误:
ORIGINAL EXCEPTION: TypeError: Cannot read property 'areEqual' of null
I would use the Elvis operator for this: 我将为此使用Elvis运算符:
<div *ngIf="!myForm.valid">
<p *ngIf="myForm.errors?.areEqual"> <-----
The two passwords do not match
</p>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.