2

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.

1 Answer 1

1

update

This was fixed in beta.16 https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26

original

It's a known issue that the required validator doesn't work properly for <input type="number">

See also

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the prompt feedback. I think the Angular2 official documentation should be updated to mention this! Is the same lack of support also for the other HTML5 types, such as date, etc (w3schools.com/html/html_form_input_types.asp)? Is there any plan to support it?
I guess that is supposed to get fixef instead of documented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.