組件代碼-
ngOnInit(): void {
this.form = this.fb.group({
currentPassword: ['', [Validators.required], [this.matchCurrentPassword]]。
newPassword: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(12)]。
confirmPassword: ['', [Validators.required]].
}
, { validator: this.ConfirmedValidator('newPassword', 'confirmPassword') }
)
}
matchCurrentPassword = (
控制。AbstractControl
): 觀察<ValidationErrors | ValidationErrors> => {
return this.userService.matchCurrentPassword(localStorage.getItem("userId"), control.value)
.管道
(tap(x => { console.log(" response:", x) }),
(map((x: any) => { return x.isExecute ? { matches: true } : { matches: false } : { matches: false }; }))
)
}
ConfirmedValidator(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.confirmedValidator) {
回傳。
}
如果(control.value !== matchingControl.value) {
matchingControl.setErrors({ confirmedValidator: true })。
} else {
matchingControl.setErrors(null)。
}
}
}
Html代碼-
<mat-form-field appearance="outline" fxFlex="1 1 calc(100% - 10px) "fxFlex.lt-md="1 1 calc(100% - 10px)" fxFlex.lt-sm="100%" fxFlex.xs="100%" class="from-color" >
<mat-label class="label-padding">輸入當前密碼</mat-label>
<input type="password" class="label-padding" type="text" style="-webkit-text-security: disc;" matInput placeholder="Current Password" formControlName="currentPassword" />
<mat-error *ngIf="currentPassword.errors?.required && currentPassword.touched">輸入當前密碼</mat-error>
<mat-error *ngIf="currentPassword.errors?.matches==false">不匹配</mat-error>
</mat-form-field>
匹配當前密碼的驗證作業完美&;根據條件顯示錯誤資訊。但是它的輸入欄位之后仍然是無效的。
我還嘗試驗證了其他的輸入欄位。但是currentPassword仍然無效& 這導致整個表單仍然無效。
為什么會發生這種情況& 如何解決這個問題?有沒有人有什么想法?
uj5u.com熱心網友回復:
根據定義自定義驗證器,
該函式接收一個 Angular 控制元件物件,如果該控制元件的值有效,則回傳 null,或者回傳一個驗證錯誤物件。
你需要為matchCurrentPassword函式回傳null,如果驗證有效
解決方案當驗證失敗時,在
matchCurrentPassword函式中回傳{ matches: true }。
.component.ts
matchCurrentPassword = (
control: AbstractControl: control.
): Observable<ValidationErrors | null> => {
let userId = localStorage.getItem('userId')。
return this.userService。 matchCurrentPassword(userId, control.value)。pipe(
tap(x => {
console.log('response:', x) 。
}),
map((x: any) => {
return x.isExecute ? null : { matches: true };
})
);
};
.component.html
<mat-error *ngIf="currentPassword.errors?.matches">不匹配</mat-error>。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/311809.html
標籤:
