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]
 });

1 Answer 1

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],
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, just perfect. Especially just setting type to number! I will save the other option too. Highly appreciated!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.