Validators min and maximum number angular 4

14,552

Solution 1

You could write your own numeric validator. Something like this:

import { AbstractControl, ValidatorFn } from '@angular/forms';

export class NumberValidators {

    static range(min: number, max: number): ValidatorFn {
        return (c: AbstractControl): { [key: string]: boolean } | null => {
            if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {
                return { 'range': true };
            }
            return null;
        };
    }
}

Solution 2

Easiest way I found is with validators. Check this reference link:

https://angular.io/api/forms/Validators

static min(min: number): ValidatorFn
static max(max: number): ValidatorFn

Complete code example which I have implemented is as following:

For the reference component.ts

this.form = this.fb.group({
  'name' :new FormControl(null, Validators.compose([Validators.required])),
  'width':  new FormControl(null, Validators.compose([Validators.required, Validators.min(0), Validators.max(200)])),
  'height':  new FormControl(null, Validators.compose([Validators.required, Validators.min(0), Validators.max(200)]))
});

component.html

<div *ngIf="width.errors?.min || width.errors?.max" class="error">Width is not valid.</div>
<div *ngIf="height.errors?.min || height.errors?.max" class="error">Height is not valid.</div>
Share:
14,552
Manspof
Author by

Manspof

Updated on July 19, 2022

Comments

  • Manspof
    Manspof almost 2 years

    is there any option to make validator min and maximum number, i.e number between 0 to 200?

    dialog-result-component.ts

    import { Component, OnInit } from '@angular/core';
    import { MdDialog, MdDialogRef } from '@angular/material';
    import { FormGroup,FormControl,Validators,FormBuilder,  } from '@angular/forms';
    
    
    
    @Component({
      selector: 'app-dialog-result',
      templateUrl: './dialog-result.component.html',
    })
    
    export class DialogResultComponent {
    
    
      form: FormGroup;
      name = new FormControl('',Validators.required);
      width = new FormControl('',Validators.required);
      height = new FormControl('',Validators.required);
      constructor(public dialogRef: MdDialogRef<DialogResultComponent>,private fb: FormBuilder) {
    
      }
    
      ngOnInit() {
      this.form = this.fb.group({
          'name':    this.name,
          'width':   this.width,
          'height':  this.height,
        });
    }
    
      saveData(){
        this.dialogRef.close({name:this.name,width:this.width,height:this.height});
      }
    }
    

    dialog-result.component.html

           <form [formGroup]="form">
         <h3>MineSweeperwix</h3>
          <div class="mdl-dialog__content">
                    <p><mdl-textfield type="text" label="name" formControlName="name" floating-label autofocus></mdl-textfield></p>
                    <mdl-textfield type="number" formControlName="width" min="0" max="350" label="width"   floating-label autofocus></mdl-textfield>
                   <mdl-textfield type="number" formControlName="height" label="height" min="0" max="350" floating-label autofocus  error-msg="'Please provide a correct email!'"></mdl-textfield>
          </div>
          <div class="mdl-dialog__actions">
            <button mdl-button (click)="saveData()" mdl-button-type="raised" mdl-colored="primary" mdl-ripple [disabled]="!form.valid">Save</button>
            <button mdl-button (click)="dialogRef.close(dd)" mdl-button-type="raised" mdl-ripple>Cancel</button>
          </div>
       </form>
    

    the min and maximum into the the mdl-text-field

    min="0" max="200" floating-label autofocus
    

    limit the user to write number between the range but it let to press the save button and that's not what i want to do. i want the user can press save button just if all the form is valid.

    what I tried to do is

    dialog.result.component.ts

        import { Component, OnInit } from '@angular/core';
    import { MdDialog, MdDialogRef } from '@angular/material';
    import { FormGroup,FormControl,Validators,FormBuilder,ValidatorFn,AbstractControl  } from '@angular/forms';
    import { NumberValidators } from '../validators/NumberValidators.module';
    
    
    @Component({
      selector: 'app-dialog-result',
      templateUrl: './dialog-result.component.html',
    })
    
    export class DialogResultComponent {
    
    
      form: FormGroup;
      name = new FormControl('',Validators.required);
      width = new FormControl('',[Validators.required,NumberValidators.range(3,300)]);
      height = new FormControl('',[Validators.required,NumberValidators.range(3,300)]);
      constructor(public dialogRef: MdDialogRef<DialogResultComponent>,private fb: FormBuilder) {
    
      }
    
      ngOnInit() {
      this.form = this.fb.group({
          'name' :this.name,
          'width': this.width,
          'height':  this.height
        });
    }
    
      saveData(){
        console.log(this.name.value);
        this.dialogRef.close({name:this.name.value,width:this.width.value,height:this.height.value});
      }
    
    }
    

    NumberValidators.module.ts

    import { AbstractControl, ValidatorFn } from '@angular/forms';
    
    export class NumberValidators {
    
        static range(min: number, max: number): ValidatorFn {
            console.log(min+max);
            return (c: AbstractControl): { [key: string]: boolean } | null => {
                if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {
                    return { 'range': true };
                }
                return null;
            };
        }
    

    }

    but it's not works fine, anyone have any suggestion?

  • Manspof
    Manspof about 7 years
    hey Deborah, i took this validator and try to use it. it shows me an error . i used it like that width = new FormControl('',Validators.required,NumberValidators.range(3,‌​300));
  • Manspof
    Manspof about 7 years
    it shows "argument of type ValidatorFn" is not assignable to parameter of type 'asynceValidatorFn .....
  • DeborahK
    DeborahK about 7 years
    The second argument is for normal validators and the third argument is for async validators. This isn't an async validator. You need to add it as part of the second argument by passing the second argument as an array. Something like this: [validators.required, NumberValidators.range(3,300)]