gpt4 book ai didi

angular - 从数据模型创建 FormBuilder 组时如何添加验证器?

转载 作者:行者123 更新时间:2023-12-04 03:09:12 26 4
gpt4 key购买 nike

根据 the Reactive Forms documentation ,我可以从

重构我的 FormGroup 定义
this.heroForm = this.fb.group({
name: ['', Validators.required ],
address: this.fb.group({
street: '',
city: '',
state: '',
zip: ''
})
});

export class Address {
street = '';
city = '';
state = '';
zip = '';
}

this.heroForm = this.fb.group({
name: ['', Validators.required ],
address: this.fb.group(new Address())
});

如果我从数据模型创建表单组,我该如何添加验证器?

最佳答案

根据 the FormBuilder source , group 采用第二个 extra 参数,您可以在其中定义验证器。 Todd Motto has an article on how to use it这表明以下内容:

export class Address {
street = '';
city = '';
state = '';
zip = '';
}

this.heroForm = this.fb.group({
name: ['', Validators.required ],
address: this.fb.group(new Address(), { validator: this.myValidator })
});

this.myValidator = (control: AbstractControl): {[key: string]: boolean} => {
const city= control.get('city');
const state= control.get('state');
...
if (allTheControlsAreValid) return null;
else return { myCustomError: foo};
};

这允许您验证表单组,但不能验证控件。如果要在各个控件上设置验证器,可以在创建 formGroup 后以编程方式设置它们:

this.heroForm.get('address').get('city').setValidators([Validators.required, Validators.maxLength(30)]);

关于angular - 从数据模型创建 FormBuilder 组时如何添加验证器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46587210/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com