Home > other >  HTML / Angular input validation - Allow numbers and dots, not dashes
HTML / Angular input validation - Allow numbers and dots, not dashes

Time:12-02

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

CodePudding user response:

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('.', '           
  • Related