微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

角度中的验证器显示角度中的弃用错误

如何解决角度中的验证器显示角度中的弃用错误

下面是我的验证实用程序

import { FormGroup } from '@angular/forms';

// custom validator to check that two fields match
export function MustMatch(controlName: string,matchingControlName: string) {
    return (formGroup: FormGroup) => {
        const control = formGroup.controls[controlName];
        const matchingControl = formGroup.controls[matchingControlName];

        if (matchingControl.errors && !matchingControl.errors.mustMatch) {
            // return if another validator has already found an error on the matchingControl
            return;
        }

        // set error on matchingControl if validation fails
        if (control.value !== matchingControl.value) {
            matchingControl.setErrors({ mustMatch: true });
        } else {
            matchingControl.setErrors(null);
        }
    }
}

这是组件类

this.userForm = this.formBuilder.group({

      id: [0],userName: ['',[Validators.required,Validators.minLength(3),Validators.maxLength(30)]],password: ['',Validators.minLength(5),confirmPassword: ['',..
     
      },{
        validator: MustMatch('password','confirmPassword')  --After adding this i am gtting deprecated error
    });

ablove 代码工作正常..但现在这个.formBuilder.group 已被弃用..

请让我提供任何替代解决方案..

enter image description here

编辑:

import { AbstractControl } from '@angular/forms';
import { Injectable } from '@angular/core';

@Injectable()
export class ValidationService {

    getValidatorErrorMessage(name: string,value?: any) {
        const config = {
            'required': 'required','email':'Invalid email address','invalidPassword': 'This regex can be used ','mustMatch': `Passwords must match`,};
        return config[name];
    }

    
    password(control: AbstractControl) {
        if (control.value.match(/^(?=[^\d_].*?\d)\w(\w|[!@#$%]){7,20}/)) {
            return null;
        } else {
            return { 'invalidPassword': true };
        }
    }
 //can i move mustmatch function here?
}

这是我的验证服务..是否可以在验证服务中使用..

解决方法

您的验证器函数需要返回 ValidationErrors | null

export function MustMatch(controlName: string,matchingControlName: string) {
    return (formGroup: FormGroup) => {
        const control = formGroup.controls[controlName];
        const matchingControl = formGroup.controls[matchingControlName];

        if (matchingControl.errors && !matchingControl.errors.mustMatch) {
            // return if another validator has already found an error on the matchingControl
            return null;
        }

        // set error on matchingControl if validation fails
        if (control.value !== matchingControl.value) {
            matchingControl.setErrors({ mustMatch: true });
           return { mustMatch: true };
        } else {
            matchingControl.setErrors(null);
           return null;
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。