Angular响应式表单自定义验证未在触摸时触发。
创始人
2024-10-30 08:30:14
0

这通常是因为表单控件未被标记为“已触摸”。为了解决这个问题,您可以手动标记表单控件为“已触摸”,以便触发自定义验证。 下面是一个示例,其中验证函数“myCustomValidator”将在触摸表单控件时触发:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.myForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]]
    });
  }

  // 自定义验证函数
  myCustomValidator(controlName: string) {
    const control = this.myForm.get(controlName);
    // 检查表单控件是否被触摸
    if (control.touched && control.errors) {
      // ... 做出你的自定义验证逻辑 ...
      return { myCustomError: true };
    } else {
      return null;
    }
  }
}

在模板中,您需要手动标记表单控件为“已触摸”:

请填写电子邮件地址。

电子邮件地址格式不正确。

自定义验证错误。

相关内容

热门资讯

透视安装!德普之星辅助器,hh... 透视安装!德普之星辅助器,hhpoker怎么开透视,一分钟教会你(有挂介绍);1、打开软件启动之后找...
透视辅助!aapoker透视软... 透视辅助!aapoker透视软件,德朴之星脚本,一分钟揭秘(有挂介绍);所有人都在同一条线上,像星星...
透视神器!wpk透视辅助方法,... 透视神器!wpk透视辅助方法,hhpoker透视方法,分享给玩家(有挂辅助挂);1、每一步都需要思考...
透视模拟器!wpk辅助器安装,... 透视模拟器!wpk辅助器安装,wepoekr底牌透视,重大通报(有挂方法)1. ai辅助创建新账号,...
透视好友房!aapoker有脚... 透视好友房!aapoker有脚本吗,aapkoer德州辅助挂下载,如何分辨真伪(有挂教程);1、首先...
透视透视!wpk辅助软件,hh... 透视透视!wpk辅助软件,hhpoker透视脚本下载,了解一下(有挂详情);一、AI软件牌型概率发牌...
透视好友!wepoker透视版... 透视好友!wepoker透视版下载,aapoker辅助工具存在吗,一分钟了解(有挂教学)1、aapo...
透视免费!智星德州菠萝透视插件... 透视免费!智星德州菠萝透视插件工具,wepoker底牌透视脚本,最新通报(有挂辅助挂);1、智星德州...
透视免费!aapoker脚本怎... 透视免费!aapoker脚本怎么用,wepoker底牌透视脚本,最新通报(有挂了解)1、进入游戏-大...
透视黑科技!wepoker透视... 透视黑科技!wepoker透视底牌脚本,德普之星有没有挂,总算了解(有挂辅助挂)1、全新机制【软件透...