2

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

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Jina devi
  • 55
  • 5
  • Please include clarification, further explanation etc. into your answer. Don't use [comments](https://stackoverflow.com/help/privileges/comment) for that. Comments should be used for asking for more information or for suggesting improvements. – Joey May 03 '19 at 11:17
  • I think these should be two different things: a custom directive and/or a custom validator – jcuypers May 03 '19 at 11:17
  • Is there any error in console? – Yash Rami May 03 '19 at 11:25
  • just put `myNumberOnly` (not myNumberOnly=yes). You use [myNumberOnly]="variable" if your directive has an input. You can see an example in https://stackoverflow.com/questions/54460923/angular-2-restrict-input-field – Eliseo May 03 '19 at 12:16

1 Answers1

1

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;
  }
}
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Shubham
  • 462
  • 2
  • 8