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

4
  • Please include clarification, further explanation etc. into your answer. Don't use comments for that. Comments should be used for asking for more information or for suggesting improvements. Commented May 3, 2019 at 11:17
  • I think these should be two different things: a custom directive and/or a custom validator Commented May 3, 2019 at 11:17
  • Is there any error in console? Commented May 3, 2019 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 stackoverflow.com/questions/54460923/… Commented May 3, 2019 at 12:16

1 Answer 1

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.