I need simple validation for phone number.This filed is already inside the reactive form.so I have written custom directive and I implemented but its not working not even detecting

I created separate directive file and I injected but no use:(

directive.ts

//custom directive for phone number
import { Directive, ElementRef, Output, EventEmitter, HostListener, Input } from '@angular/core';

@Directive({
    selector: '[myNumberOnly]'
})

export class NumberOnlyDirective {

    private regex: RegExp = new RegExp(/^-?[0-9]+(\.[0-9]*){0,1}$/g);
    private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-'];
    constructor(private el: ElementRef) {
    }
    @HostListener('keydown', ['$event'])
    keydown(event: KeyboardEvent) {
        // Allow Backspace, tab, end, and home keys
        if (this.specialKeys.indexOf(event.key) !== -1) {
            return;
        }
        let current: string = this.el.nativeElement.value;
        let next: string = current.concat(event.key);
        if (next && !String(next).match(this.regex)) {
            event.preventDefault();
        }
    }
}

HTML

html section

<form [formGroup]="arrangeFE">
 <input myNumberOnly="true" type="text" formControlName="FEName" class="input_Align" name="" [(ngModel)]="arrangeFieldEngineer.name" [readonly]="arrangeFieldEngineer.isReadonly"  placeholder="Enter FE Name"
         autocomplete="off">
    <form>

need custom validation for phone number and It should be with in the reactive form.When user enters the correct number then only it should pass ng-valid

1 Answers

1
Shubham On

Try this:

export class CustomValidator {
  // Number only validation
  static numeric(control: AbstractControl) {
    let val = control.value;

    if (val === null || val === '') return null;

    if (!val.toString().match(/^[0-9]+(\.?[0-9]+)?$/)) return { 'invalidNumber': true };

    return null;
  }
}