如果至少一个字段具有值,则将所需的验证添加到反应式FormGroup的所有控件中

时间:2018-12-06 07:29:35

标签: angular typescript angular-reactive-forms angular-forms

我有一个很少有控件的表单组,仅当至少一个字段具有值时,才需要所有字段。即,用户可以将所有字段保留为空白或在所有字段中输入数据。并且每个控件都需要经过验证才能在其下方显示所需的错误。

我尝试在内置的必需验证器的帮助下为此构建自定义验证器,但它仅在验证当前控件。

//in state
 this.state = {
  startDate: moment(),
  endDate: moment(),
}

//My onChange handler function    
handleDateChange(dateName, dateValue) {
    let { startDate, endDate } = this.state;
    if (dateName === 'startDateTime') {
      startDate = dateValue;
    } else {
      endDate = dateValue;
    }
    this.setState({
      startDate,
      endDate,
    });
  }

// Date Picker component
<DatePicker
    id="start-date-time"
    name="startDateTime"
    className="form-control"
    selected={this.state.startDate}
    value={this.state.startDate}
    onChange={date => this.handleDateChange('startDateTime', date)}
    showTimeSelect
    timeFormat="HH:mm"
    timeIntervals={15}
    dateFormat="YYYY-MM-DD, h:mm a"
    timeCaption="time"
  />
//other use of Date picker
<DatePicker


 id="end-date-time"
  name="endDateTime"
  className="form-control"
  selected={this.state.endDate}
  value={this.state.endDate}
  onChange={date => this.handleDateChange('endDateTime', date)}
  placeholderText="choose end date of event"
  isClearable={true}
  showTimeSelect
  timeFormat="HH:mm"
  timeIntervals={15}
  dateFormat="YYYY-MM-DD, h:mm a"
  timeCaption="time"
/>

Here是我的实现。

2 个答案:

答案 0 :(得分:4)

为什么不简单

this.myForm.get('myFirstControl').valueChanges.subscribe(value => {
  for (const control of this.myForm.controls) {
    if (!value) { control.setValidators([]); }
    else { control.setValidators([Validators.required]); }
  }
});

答案 1 :(得分:1)

这是一种不同的方法,但是您可以根据这样的条件动态添加所需的验证器

 <input type="text" formControlName="user" [required]="hasValue()">

组件

  hasValue(){
    return Object.values(this.form.value).join('').trim().length > 0
  }

stackblitz demo