0

I just did my first forms validation in Angular and it works really nice. Some of my input must be numbers only, and I would expect that to be fairly easy. However I only found some pretty complex extensions can this be true? Is there not an easy way to a simple validation for numbers?

this.registerForm = this.formBuilder.group({
   name: ['', Validators.required],
   type: ['', Validators.required],
   imo: ['', [Validators.required]],
   dwt: ['', Validators.required],
   built: ['', Validators.required],
   yard: ['', Validators.required],
   flag: ['', Validators.required]
 });
Thomas Segato
  • 4,567
  • 11
  • 55
  • 104

1 Answers1

1

If you want your input to be numbers only, just use the right type of input in your template:

<input type="number" formControlName="built" ... >

You don't need to add a validator for this if you can restrict the input to numbers only.

However, if you can't change the input type, then you can use the pattern validator with a regex to check if the value is a number:

Validators.pattern(/^-?(0|[1-9]\d*)?$/)

Check this SO question for more info about the use of the pattern validator for numbers.

You can also wrap this into a custom validator:

import { FormControl } from '@angular/forms';

function numberOnly(control: FormControl) {
  const regex = /^-?(0|[1-9]\d*)?$/;
  return regex.test(control.value) ? null : { number: false };
}

which you can use it like this:

built: ['', Validators.required, numberOnly],
jo_va
  • 13,504
  • 3
  • 23
  • 47