Angular2 - 有条件创建的输入字段的表单验证

时间:2016-04-04 10:15:20

标签: javascript angularjs forms validation angular

我正在创建一个简单的表单,用户可以选择两个可能的值,即LocalForeigner。如果用户没有选择任何内容,则会生成invalid形式的值。如果用户选择Local,则表单将变为valid。如果用户选择Foreigner,则会出现一个新字段,用于将国家/地区作为用户输入,这也是必需的。如果用户在国家/地区输入字段中未输入任何内容,则会生成invalid

表单

我尝试创建如下表单:

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {Control,ControlGroup,FormBuilder,FORM_DIRECTIVES,Validators} from 'angular2/common';

@Component({
  selector: 'app',
  template: `
  <form [ngFormModel]="form" >
    <select [ngFormControl]="nationalityCtrl" >
      <option *ngFor="#nationality of nationalities" [value]="nationality" >{{nationality}}</option>
    </select><br>
    <input *ngIf="form.value.nationality == 'Foreigner'" type="text" [ngFormControl]="countryCtrl" placeholder="Country Name" />
    <button class="btn btn-primary" [disabled]="!form.valid" >Submit</button>
  </form>
  `,
  directives: [FORM_DIRECTIVES]
})
class MainApp{
  public nationalities = ["Foreigner","Local"];
  public form:ControlGroup;
  public nationalityCtrl:Control;
  public countryCtrl:Control;

  constructor(private _fb:FormBuilder){
  var self = this;

  this.nationalityCtrl = new Control("",Validators.compose([Validators.required]));
  this.countryCtrl = new Control("",Validators.compose([function(control:Control){
      if(self.nationalityCtrl.value == "Foreigner" && !control.value){
        return {invalid: true};
      }
    }]));

    this.form = this._fb.group({
      nationality: this.nationalityCtrl,
      country: this.countryCtrl
    });
  }
}
bootstrap(MainApp);

但是只要我选择Foreigner选项,我就会在控制台上收到以下错误:

  

EXCEPTION:MainApp @ 6:36中的表达式'!form.valid'在之后发生了变化   它被检查了。上一个值:'false'。当前值:'true'in   [!MainApp @ 6:36中的form.valid]

我在plunker here上重新产生了问题,您可以在控制台上看到错误消息。

1 个答案:

答案 0 :(得分:6)

我会为整个表单定义一个全局验证器,因为验证器依赖于两个字段:

this.form = this._fb.group({
  nationality: this.nationalityCtrl,
  country: this.countryCtrl
}, {
  validator: (control:Control) => {
    var nationalityCtrl = control.controls.nationality;
    var countryCtrl = control.controls.country;
    if(nationalityCtrl.value == "Foreigner" && !countryCtrl.value){
      return {invalid: true};
    }
  }
});

请参阅此plunkr:https://plnkr.co/edit/Cksiv2UFbWoVJv2VwPwh?p=preview

有关详细信息,请参阅此问题: