【发布时间】:2018-03-25 23:57:39
【问题描述】:
当我需要在注册表单中检查相等的两个字段时,我遇到了这种情况。它是输入密码和重复密码。我为此任务创建了我的验证器。但是对于相等的两个字符串检查,我需要在我的验证器中获取form 对象:
export class RegistrationComponent implements OnInit {
private formSubmitAttempt: boolean;
form: FormGroup;
constructor(private fb: FormBuilder,
private authService: AuthService) {
}
ngOnInit() {
this.form = this.fb.group({ // {5}
username: ['', [Validators.required, Validators.minLength(5)]],
password: ['', [Validators.required, Validators.minLength(5)]],
dpassword: ['', [Validators.required, this.validateMatchPasswords.bind(this)]],
email: ['', [Validators.required, Validators.email]]
});
}
validateMatchPasswords(control: FormControl) {
const err = this.form.get('password').value === this.form.get('dpassword').value;
return {
error: false
};
}
onSubmit() {
...
}
}
validateMatchPasswords - 我的验证器方法,但它会生成
错误:
ERROR TypeError: Cannot read property 'get' of undefined
at RegistrationComponent.validateMatchPasswords (registration.component.ts:32)
at eval (forms.js:759)
at Array.map (<anonymous>)
at _executeValidators (forms.js:759)
at FormControl.eval [as validator] (forms.js:711)
at FormControl.AbstractControl._runValidator (forms.js:3433)
at FormControl.AbstractControl.updateValueAndValidity (forms.js:3387)
at new FormControl (forms.js:3905)
at FormBuilder.control (forms.js:7899)
at FormBuilder._createControl (forms.js:7965)
尽管我在ngOnInit() -this.validateMatchPasswords.bind(this) 中绑定了this,但form 对象在validateMatchPasswords 方法中不可用
为什么会出现此错误^以及如何解决此问题?谢谢!
我使用angular.material 来构建我的组件:
<div class="signin-content">
<mat-card>
<mat-card-content>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
...
<mat-input-container class="full-width-input">
<input matInput type="password" placeholder="Create new password"
formControlName="password" required>
<mat-error *ngIf="isFieldInvalid('password')">
Please inform your password. Minimum 5 symbol.
</mat-error>
</mat-input-container>
<mat-input-container class="full-width-input">
<input matInput type="password" placeholder="Repeat you're password"
formControlName="dpassword" required>
<mat-error *ngIf="isFieldInvalid('dpassword')">
Passwords do not match
</mat-error>
</mat-input-container>
...
</form> </mat-card-content>
</mat-card>
</div>
【问题讨论】:
-
你可以为你的代码创建提琴手/codepen吗?
-
@VicJordan 抱歉不明白。你对 fiddler/codepen 意味着什么?
-
创建您的代码的
executable code snippet
标签: javascript angular5 angular4-forms