You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular FormBuilder.group数组验证器报错,求extra参数正确用法

Fixing "this.validator is not a function" with Angular FormBuilder's extra parameter

Hey there! I’ve run into this exact issue before, so let’s break down what’s going wrong and how to fix it.

The Root Cause

The extra parameter in FormBuilder.group() is not meant to be a validator or array of validators directly—it’s an object that holds configuration properties like validators, asyncValidators, and updateOn.

If you pass an array of validators directly as the second argument (like group(controls, [Validators.minLength(3)])), Angular tries to treat that array as a validator function, which throws the "this.validator is not a function" error.

And if you pass a single validator directly (instead of wrapping it in the extra object), Angular treats it as the extra configuration object—since validator functions don’t have a validators property, no validation actually gets applied, hence your "validation not working" problem.

Correct Usage of the Extra Parameter

You need to wrap your validators inside the validators property of the extra object. Here’s how to do it properly:

1. Single Validator

import { FormBuilder, Validators } from '@angular/forms';

// Inside your component
constructor(private fb: FormBuilder) {}

ngOnInit() {
  this.myForm = this.fb.group({
    username: ['', Validators.required]
  }, {
    // Extra parameter is an object with validators property
    validators: Validators.minLength(5) 
  });
}

2. Multiple Validators (Array)

// Define a custom validator if needed
function passwordMatchValidator(form: FormGroup) {
  const password = form.get('password')?.value;
  const confirmPassword = form.get('confirmPassword')?.value;
  return password === confirmPassword ? null : { passwordMismatch: true };
}

// Build the form
this.myForm = this.fb.group({
  password: ['', Validators.required],
  confirmPassword: ['', Validators.required]
}, {
  validators: [Validators.minLength(8), passwordMatchValidator] // Array of validators
});

3. Adding Other Extra Configurations

You can also set the validation trigger timing with updateOn:

this.myForm = this.fb.group({
  email: ['', [Validators.required, Validators.email]]
}, {
  validators: (form: FormGroup) => {
    return form.get('email')?.value.includes('@company.com') ? null : { invalidDomain: true };
  },
  updateOn: 'blur' // Validate only when the input loses focus
});

Verifying the Fix

After adjusting your code to wrap validators in the validators property of the extra object, you should:

  • No longer see the "this.validator is not a function" error
  • Have your validators properly applied (check myForm.invalid or myForm.errors to confirm)

内容的提问来源于stack exchange,提问作者Dharmvir Tiwari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:33:54