Javascript – Angular 2 Form Validation For Numbers minimum and maximum

angularformsjavascripttypescriptvalidation

I have a form with input boxes. The input boxes are in both type text and numbers. And I have to validate them and I followed this tutorial and tried to validate them.

According to that if I have to validate a string then I can use the control group as follows.

constructor(fb: FormBuilder){
    this.complexForm = fb.group({
      'firstName' : [null, Validators.required],
      'lastName': [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10)])]
})

And the HTML code for this as follows…

<form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
      <div class="form-group">
        <label>First Name:</label>
        <input class="form-control" type="text" placeholder="John" [formControl]="complexForm.controls['firstName']">
      </div>
      <div class="form-group">
        <label>Last Name</label>
        <input class="form-control" type="text" placeholder="Doe" [formControl]="complexForm.controls['lastName']">
      </div>
      <div class="form-group">
        <button type="submit" class="btn btn-default">Submit</button>
      </div>
</form>

But I have to validate a number type input box also as the following example.

<form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
          <div class="form-group">
            <label>Age:</label>
            <input class="form-control" type="number"  [formControl]="complexForm.controls['age']">
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-default">Submit</button>
          </div>
</form>

But Problem is there is no option for Validators to select what is minimum value and maximum value for the input.

are there someone has a solution for this issue?

Thanks.

Best Answer

The current version of angular 4 now has min and max validators

So it is as simple as writing

this.complexForm = fb.group({
   age:[null,[Validators.required, Validators.min(5),Validators.max(90)]],
})

Remember it is on the @angular/forms repo

$: npm uninstall @angular/forms --save
$: npm install @angular/forms --save