简体   繁体   English

Angular formBuilder 组弃用自定义验证

[英]Angular formBuilder group deprecate whit custom validation

I am getting this error when I place my custom validation, and try naming the validation as "as AbstractControlOption" and modifying the code in different ways but nothing works当我放置自定义验证时出现此错误,并尝试将验证命名为“as AbstractControlOption”并以不同方式修改代码但没有任何效果

This API is not typesafe and can result in issues with Closure Compiler renaming.这个 API 不是类型安全的,可能会导致 Closure Compiler 重命名问题。 Use the FormBuilder#group overload with AbstractControlOptions instead.改用带有 AbstractControlOptions 的 FormBuilder#group 重载。 Note that AbstractControlOptions expects validators and asyncValidators to be valid validators.请注意,AbstractControlOptions 期望验证器和 asyncValidators 是有效的验证器。 If you have custom validators, make sure their validation function parameter is AbstractControl and not a sub-class, such as FormGroup.如果您有自定义验证器,请确保它们的验证 function 参数是 AbstractControl 而不是子类,例如 FormGroup。 These functions will be called with an object of type AbstractControl and that cannot be automatically downcast to a subclass, so TypeScript sees this as an error.这些函数将使用 object 类型的 AbstractControl 调用,并且不能自动向下转换为子类,因此 TypeScript 将此视为错误。 For example, change the (group: FormGroup) => ValidationErrors|null signature to be (group: AbstractControl) => ValidationErrors|null.例如,将 (group: FormGroup) => ValidationErrors|null 签名更改为 (group: AbstractControl) => ValidationErrors|null。

this is my custom validation这是我的自定义验证

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

@Injectable({
  providedIn: 'root'
})
export class ValidatorService {

  public nombreApellidoPattern:string = '([a-zA-Z]+) (.+[a-zA-Z])';
  public emailPattern: string = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$";

  constructor() { }

  noPuedesSerYo (control:FormControl):ValidationErrors | null{
    const valor:string =control.value?.trim().toLowerCase();
    if(valor==='pepepepon'){
      return {noYo:true};
    }
    return null;
  }

  camposIguales(campo1:string, campo2:string){
    return (control:AbstractControl)=>{
      const pass1=control.get(campo1)?.value;
      const pass2=control.get(campo2)?.value;

      console.log(campo1)

      if(pass1!==pass2){  
        control.get(campo2)?.setErrors({noIguales:true});
        return {noIguales:true};
      }

      control.get(campo2)?.setErrors(null);
      return null;
    }
  }

}

and here i use this validation but i dont know why this code is not working:(在这里我使用了这个验证,但我不知道为什么这段代码不起作用:(

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ValidatorService } from 'src/app/shared/validator/validator.service';
//import { emailPattern, nombreApellidoPattern, noPuedesSerYo } from '../../../shared/validator/validaciones';

@Component({
  selector: 'app-registro',
  templateUrl: './registro.component.html',
  styleUrls: ['./registro.component.css']
})
export class RegistroComponent implements OnInit {

  miFormulario:FormGroup = this.fb.group({
    nombre:['',[Validators.required, Validators.pattern(this.validatorService.nombreApellidoPattern)]],
    email:['',[Validators.required, Validators.pattern(this.validatorService.emailPattern)]],
    username:['',[Validators.required, this.validatorService.noPuedesSerYo]],
    password:['',[Validators.required,Validators.minLength(6)]],
    password2:['',[Validators.required]]
  },{
    Validators:this.validatorService.camposIguales('password','password2')
  });

  constructor(private fb:FormBuilder, private validatorService:ValidatorService){}

  ngOnInit(): void {
    this.miFormulario.reset({
      nombre:'',
      email:'',
      username:'',
      password:'',
      password2:''
    })
  }

  campoInvalido(campo:string){
    return this.miFormulario.get(campo)?.invalid && this.miFormulario.get(campo)?.touched;
  }

  submitForm(){
    this.miFormulario.markAllAsTouched();
  }

}

Fix your code accordingly, I hope so you problem solved: https://stackblitz.com/edit/angular-ivy-2qfmub?file=src/app/registro-component/registro.component.ts相应地修复你的代码,我希望你的问题解决了: https://stackblitz.com/edit/angular-ivy-2qfmub?file=src/app/registro-component/registro.component.ts

miFormulario: FormGroup = this.fb.group(
        {
          nombre: [
            '',
            [
              Validators.required,
              Validators.pattern(this.validatorService.nombreApellidoPattern),
            ],
          ],
          email: [
            '',
            [
              Validators.required,
              Validators.pattern(this.validatorService.emailPattern),
            ],
          ],
          username: [
            '',
            [Validators.required, this.validatorService.noPuedesSerYo],
          ],
          password: ['', [Validators.required, Validators.minLength(6)]],
          password2: ['', [Validators.required]],
        },
        {
          validators: [
            this.validatorService.camposIguales('password', 'password2'),
          ],
        }
      );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM