Angular 2 Custom Validator: check if the input value is an integer?

AIon picture AIon · Sep 30, 2016 · Viewed 14.9k times · Source

In an Angular2 project I need to validate some inputs. How to easily check if an input value is an integer?

I tried using Number(control.value) which returns 0 for an empty field - not good.

or parseInt(control.value,10) which dis-considers spaces:

If i have something like: 1 space 0,24 = 1 ,024 it returns 1 - which passes the validator with no errors.

Lodash functions like: _.isInteger(control.value) or _.isNumeric(control.value) // return false every time -which is expected, because an input value is a string not a number.

Combining methods like this creates a messy function with many if/else statements, and even then, I'm not sure i get all the edge cases. I definitely need a more straight forward approach. Any ideas?

Answer

AIon picture AIon · Sep 30, 2016

This is the cleanest way i found so far:

app.component.html:

<input formControlName="myNumber">

app.component.ts:

export class AppComponent {
    myNumber:FormControl

    constructor(private _ValidatorsService: ValidatorsService){
    }

    this.myNumber= new FormControl('defaultValue',
        [ Validators.required, this._ValidatorsService.isInteger ]);
}

validators.service.ts:

function check_if_is_integer(value){
   // I can have spacespacespace1 - which is 1 and validators pases but
   // spacespacespace doesn't - which is what i wanted.
   // 1space2 doesn't pass - good
   // of course, when saving data you do another parseInt.

   return ((parseFloat(value) == parseInt(value)) && !isNaN(value));

}

@Injectable()
export class ValidatorsService {

   public isInteger = (control:FormControl) => {

        // here, notice we use the ternary operator to return null when value is the integer we want.
        // you are supposed to return null for the validation to pass.

        return check_if_is_integer(control.value) ? null : {
           notNumeric: true
        }
   }

}

Enjoy!