Solved: validators number only in reactive form

Sure, I’ll do my best to provide a detailed answer that fits your criteria.

Reactive forms in Angular are a way to create and manage forms in a reactive style. Reactive forms are more robust and offer a lot more functionality and control over information entered into your forms. Reactive forms are a mainstay in modern Angular development, offering a slew of advantages over its counterpart, Template-driven forms.

Validators are a critical part of successful responsive form implementation. They ensure data entered into forms is valid and useful. This article will walk you through creating number only validators in a reactive form.

The solution to prohibiting non-numeric input lies in creating a custom validator.

Creating a NumberOnly Validator

A custom validator in Angular is simply a function that receives a control and synchronously returns either a set of validation errors or null. Below is a step-by-step guide on creating a custom number-only validator:

function numberOnlyValidator(control: AbstractControl): { [key: string]: boolean } | null {
   if (control.value && !Number(control.value)) {
       return { 'numberOnly': true };
   return null;

Integrating NumberOnly Validator to Your Reactive Form

Now let’s integrate this validator to our reactive form. In the component Ts file where you are creating the reactive form, import the custom validator:

this.myForm ={
  numberInput: ['', [Validators.required, numberOnlyValidator]]

Displaying Error Message in the View

Finally, let’s display an error message in the view when non-numeric input is entered:

<div *ngIf="myForm.controls.numberInput.errors?.numberOnly">Numbers only please!</div>

You can observe the error when you try to input non-numeric characters.

Additional Libraries for More Complex Validation

There are libraries such as ng2-validation and angular2-text-mask that offer a more elaborate solution to handle number validation among other intricate validation needs. However, the custom validator outlined in this guide is simpler and feasible for a number-only validation scenario without having to bring in external dependencies.

Similar Built-in Validators in Angular

Angular offers some similar built-in validators like the maxLength validator, minLength validator, required validator, amongst others. Although none of them meet the need for a number-only validation scenario, they can be helpful in other circumstances. You just need to apply them as we have done above.

Related posts:

Leave a Comment