验证类型编号的输入在Angular2

时间:2016-04-16 17:53:38

标签: angular angular2-forms angular2-formbuilder

我正在尝试将类型为number的输入字段验证为非空。验证成功虽然它是空的。

如果输入字段的类型文本成功。以下是结合两种情况的示例:

@Component({
  ...
})
export class MyComponent {

  form: ControlGroup;
  name: Control;
  duration: Control;


  constructor(private _formBuilder: FormBuilder) {
      let thisComp = this;

      thisComp.name = new Control('', Validators.compose([Validators.required]));
      thisComp.duration = new Control('', Validators.compose([Validators.required]));

      thisComp.form = thisComp._formBuilder.group({
        name: thisComp.name,
        duration: thisComp.duration
      });

  }


  onSubmit() {
     ...
  }


}
<form [ngFormModel]="form" (submit)="onSubmit()" novalidate>


     <div>
         <label for="cntrlName">Name</label>
         <input id="cntrlName" ngControl="name" #name placeholder="Enter ..." name="name" type="text" minlength="1" maxlength="200">
         <div *ngIf="name.dirty && !name.valid && !name.pending">
            <p *ngIf="name.errors.required">Name is required.</p>
         </div>
     </div>


     <div>
         <label for="cntrlDuration">Duration (in minutes)</label>
         <input id="cntrlDuration" ngControl="duration" f#duration placeholder="Enter ..." name="duration" type="number">
         <div *ngIf="duration.dirty && !duration.valid && !duration.pending">
            <p *ngIf="duration.errors.required">Duration is required.</p>
         </div>
     </div>

</form>

在前面的例子中,即使我插入一个数字然后我将其删除,也会出现错误信息&#34;名称是必需的&#34;没有显示。

1 个答案:

答案 0 :(得分:1)