As you see it is VERY UGLY. And it can ONLY validate if the input field has value or not. I can not value the min or max length or use library like this enter link description here推荐答案FormGroup 构造函数的第二个参数允许您定义自定义组验证器.The second parameter to the FormGroup constructor lets you define a custom group validator.在组验证器中,确定是否满足有效表单的条件(即至少一个输入字段非空,并且字段长度大于 10).如果表单有效,则通过调用 control.setErrors(null) 清除各个错误.否则,返回一个自定义错误对象:{ 'atLeastOneInputFieldMustBeValid': true } 以便您可以稍后绑定到它.Within the group validator, determine if the conditions are satisfied for a valid form (i.e. at least one input field is non-empty, and has a field length greater than 10). If the form is valid, clear the individual errors by calling control.setErrors(null). Otherwise, return a custom error object: { 'atLeastOneInputFieldMustBeValid': true } so you can bind to it later. function alternativeRevenueGroupValidator(c: FormGroup) { let brandedContent = c.get('brandedContent'); let typesOfBrands = c.get('typesOfBrands'); let merchandise = c.get('merchandise'); let typeOfMerchandise = c.get('typeOfMerchandise'); let podcasts = c.get('podcasts'); let podcastIdeas = c.get('podcastIdeas'); let tours = c.get('tours'); let tourIdeas = c.get('tourIdeas'); let licensingDeals = c.get('licensingDeals'); let licensingIdeas = c.get('licensingIdeas'); if (brandedContent.valid || merchandise.valid || podcasts.valid || tours.valid || licensingDeals.valid || typesOfBrands.valid || typesOfMerchandise.valid || postcastIdeas.valid || tourIdeas.valid || licensingIdeas.valid) { brandedContent.setErrors(null); merchandise.setErrors(null); podcasts.setErrors(null); tours.setErrors(null); licensingDeals.setErrors(null); typesOfBrands.setErrors(null); typesOfMerchandise.setErrors(null); postcastIdeas.setErrors(null); tourIdeas.setErrors(null); licensingIdeas.setErrors(null); return null; } } return {'GroupNoValue': true}; }在组验证器函数中,您可以灵活地检查组内任何控件的验证标志,设置任何一个控件的错误对象,最后您可以返回具有任意数量验证标志的任何验证对象设置.Within the group validator function, you have the flexibility to inspect the validation flags of any control within the group, set the error object of any one of the controls, and finally you can return any validation object with any number of validation flags set.如果您需要至少两个字段是必填字段,并且需要超过 10 个字符,您可以执行以下操作:If you require at least two of the fields to be required, and greater than 10 charaters, you might do something like this:function alternativeRevenueGroupValidator(c: FormGroup) { var validCtls = c.controls.filter(c=> c.valid); if (validCtls.length >= 2) { c.controls.forEach((t)=> t.setErrors(null)); return null; } return {'GroupNoTwoValues': true};} 这篇关于如果组中的控件之一具有值,如何在 Angular 2 表单中进行简单的跨字段验证以通过验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-02 02:46