1

I have an AngularForm which binds the formControlName to an input field that is of type number.

I would like to accept numbers and dots only. Unfortunately the HTML attribute tag number also accepts dashes. This is something that I would like to prevent. Is there another attribute that could work within the HTML, or is there a suitable regEx expression that would only allow numbers and dots?

HTML

<input name="myNumber" step="any" type="number" formControlName="myNumber">

Angular Form / TS

myForm = this.fb.group({
  question_number: null,
});

2 Answers 2

1

you can use a custom directive with this regex /[^0-9.]/g, this should remove any other character other than numbers and dot

Directive code:

import { Directive, ElementRef, HostListener } from "@angular/core";

@Directive({
  selector: "[numberAndDot]"
})
export class NumberAndDotDirective {
  constructor(private element: ElementRef) {}

  @HostListener('input') inputChange() {

      this.element.nativeElement.value = this.element.nativeElement.value
      .replace(/[^0-9\.]/g, '')
      // Replace extra dots
      .replace('.', '%FD%')
      .replace(/\./g, '')
      .replace('%FD%', '.');
  }
}

Template code:

<input numberAndDot name="myNumber" step="any" formControlName="myNumber">
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you for the response! - I added the validator code to my component which errors when typing 'dashes' into the input. It also doesn't accept dots for decimals. (Cannot read properties of null (reading 'length'))
you do not want the error state? updated the code this should solve the error
Thanks. No luck unfortunately. Dashes are still possible to enter into the input.
ah, you want to prevent dashes from being entered
Yes correct! Sorry, I should have been more explicit.
|
1

This is like using a cannon to kill a fly, but it will work.

      myForm = this.fb.group({
         question_number: null,
      });
      this.myForm.controls['question_number'].valueChanges.subscribe(value => {
         this.myForm.controls['question_number'].setValue(value.replace(/[^0-9.]/g), ''))
      });

Is not a good practise to subscribe to an input, but this will work until you find something better (:

1 Comment

when setting value inside a valueChanges subscription use { emitEvent: false } otherwise you will end up with an infinite loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.