在Angular中以反应形式进行密码匹配验证

时间:2020-09-28 20:25:45

标签: angular

我有两个输入(newPasswordconfirmPassword),必须通过匹配它们来进行验证。 我有resetPasswordFormGroup中定义的reset-password.component

当我在MustMatch中使用formgroup自定义验证器时,出现此错误。 实际上,我对如何使用自定义验证程序感到困惑。

'{validator:(formGroup:FormGroup)=> void; }'不能分配给'ValidatorFn |类型的参数。 ValidatorFn [] | AbstractControlOptions”。 对象文字只能指定已知属性,并且'ValidatorFn |类型中不存在'validator'。 ValidatorFn [] | AbstractControlOptions'.ts(2345)

resetPasswordFormGroup = new FormGroup({
        currentPassword: new FormControl(null, Validators.required),
        newPassword: new FormControl(null, Validators.required),
        confirmNewPassword: new FormControl(null, Validators.required),
    });

    get currentPasswordFormControl() {
        return this.resetPasswordFormGroup.get('currentPassword');
    }

    get newPasswordFormControl() {
        return this.resetPasswordFormGroup.get('newPassword');
    }

    get confirmNewPasswordFormControl() {
        return this.resetPasswordFormGroup.get('confirmNewPassword');
    }
        <form [formGroup]='resetPasswordFormGroup' (ngSubmit)="onPasswordChange()">
            <mat-card-content>
                <mat-form-field class="center-text">
                    <input matInput placeholder="please enter your current password" formControlName="currentPassword" />
                    <mat-error *ngIf="currentPasswordFormControl.hasError('required')">
                        <strong>current password</strong> is required
                    </mat-error>
                </mat-form-field>
                <mat-form-field class="center-text">
                    <input matInput placeholder="please enter your new password" formControlName="newPassword" />
                    <mat-error *ngIf="newPasswordFormControl.hasError('required')">
                        <strong> new password </strong> is required  
                    </mat-error>
                </mat-form-field>
                <mat-form-field class="center-text">
                    <input matInput placeholder="please confirm your new password"
                        formControlName="confirmNewPassword" />
                    <mat-error *ngIf="confirmNewPasswordFormControl.hasError('required')">
                         <strong> confirm new password</strong> is required
                    </mat-error>
                </mat-form-field>
            </mat-card-content>

            <mat-card-actions>
                <button mat-raised-button color="primary">
                    <div *ngIf="isSubmitting" class="loading">
                        <mat-spinner [diameter]="26" color="accent"></mat-spinner>
                    </div>
                    <span *ngIf="!isSubmitting">
                        submit
                    </span>
                </button>
            </mat-card-actions>
        </form>

enter image description here

2 个答案:

答案 0 :(得分:0)

您可能做错了

根据docs,您必须按照以下步骤进行操作:

const form = new FormGroup({
  password: new FormControl('', Validators.minLength(2)),
  passwordConfirm: new FormControl('', Validators.minLength(2)),
}, passwordMatchValidator);


function passwordMatchValidator(g: FormGroup) {
   return g.get('password').value === g.get('passwordConfirm').value
      ? null : {'mismatch': true};
}

通过引用传递功能的地方

或类似:

const form = new FormGroup({
  password: new FormControl('')
  passwordConfirm: new FormControl('')
}, { validators: passwordMatchValidator, asyncValidators: otherValidator });

此外,如果您仍然想通过传递控件名称来实现,则可以提出以下内容

对于match-password.validator.ts

import { FormGroup } from '@angular/forms';
    
export function ConfirmedValidator(controlName: string, matchingControlName: string){
    return (formGroup: FormGroup) => {
        const control = formGroup.controls[controlName];
        const matchingControl = formGroup.controls[matchingControlName];
        if (matchingControl.errors && !matchingControl.errors.confirmedValidator) {
            return;
        }
        if (control.value !== matchingControl.value) {
            matchingControl.setErrors({ confirmedValidator: true });
        } else {
            matchingControl.setErrors(null);
        }
    }
}

然后您可以导入并使用它

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators} from '@angular/forms';
  
import { ConfirmedValidator } from './match-password.validator';
    
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  form: FormGroup = new FormGroup({});
  
  constructor(private fb: FormBuilder) {
  
    this.form = fb.group({
      password: ['', [Validators.required]],
      confirm_password: ['', [Validators.required]]
    }, { 
      validator: ConfirmedValidator('newPassword', 'confirmNewPassword')
    })
  }
    
  get f(){
    return this.form.controls;
  }
}

请参见Angular Validation Password and Confirm Password

答案 1 :(得分:0)

这对我不起作用,我尝试了多次,但我不知道为什么它不起作用。最后,我以这种方式做到了。谢谢你们。

resetPasswordFormGroup: FormGroup;
matcher = new MyErrorStateMatcher();

    constructor(
        private router: Router,
        private apiService: AuthApiService,
        private authSerivce: AuthService,
        private snackbar: MatSnackBar,
        private formbuilder: FormBuilder
    ) {
        this.resetPasswordFormGroup = this.formbuilder.group({
            currentPassword: ['', Validators.required],
            newPassword: ['', Validators.required],
            confirmPassword: ['', Validators.required],
        }, { validator: this.checkPasswords });
    }


    checkPasswords(group: FormGroup) {
        const pass = group.controls.newPassword.value;
        const confirmPass = group.controls.confirmPassword.value;

        return pass === confirmPass ? null : { notSame: true };
    }

以及用于检查密码是否匹配的模板代码

        <form [formGroup]='resetPasswordFormGroup' (ngSubmit)="onPasswordChange()">
            <mat-card-content>

                <mat-form-field class="center-text">
                    <input matInput placeholder="please enter your current password" formControlName="currentPassword"/>
                    <mat-error *ngIf="resetPasswordFormGroup.hasError('required', 'currentPassword')">
                        current password is required</mat-error>
                </mat-form-field>

                <mat-form-field class="center-text">
                    <input matInput placeholder="please enter your new password" formControlName="newPassword"/>
                    <mat-error *ngIf="resetPasswordFormGroup.hasError('required', 'newPassword')">
                        new password is required
                    </mat-error>
                </mat-form-field>

                <mat-form-field class="center-text">
                    <input matInput placeholder=" please confirm your new password" formControlName="confirmPassword"/>
                    <mat-error *ngIf="resetPasswordFormGroup.hasError('notSame')">
                        your new passwords are not match
                    </mat-error>
                    <mat-error *ngIf="resetPasswordFormGroup.hasError('required', 'confirmPassword')">
                        confirm new password is required
                    </mat-error>
                </mat-form-field>

            </mat-card-content>
        </form>
相关问题