简体   繁体   中英

Validating input of type number doesn't work properly in Angular2

I am trying to validate an input field of type number as non-empty. Validation succeeds although it is empty.

If the input field has type text is succeeds. Here is an example that combines both cases:

@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>

In the previous example even if I insert a number and then I delete it the error message "Name is required" is not displayed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM