如何在反应形式内实现自定义指令

时间:2019-05-03 11:12:14

标签: angular angular2-directives

我需要对电话号码进行简单的验证。该字段已经存在于响应式表单中。因此,我编写了自定义指令并实现了它,但是甚至无法检测到它

我创建了一个单独的指令文件,并且注入了但没有用:(

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部分

<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>

需要对电话号码进行自定义验证,并且应使用反应形式。当用户输入正确的电话号码时,只有该号码才能通过ng-valid

1 个答案:

答案 0 :(得分:1)

尝试一下:

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