简体   繁体   中英

how to write a directive which takes input in text box and allows only some characters based on regex?

If I have regex like [az], the directive should check regex, and allow only lowercase alphabets and if other characters are tried to type in input, then it should not type, as if it is not entered. I have gone through docs, but not getting idea.

I have forked one of the existing plunkers in order to suit your requirement.

The directive will look something like this:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[OnlyLowerCaseAlphabets]'
})
export class OnlyLowerCaseAlphabets {

  constructor(private el: ElementRef) { }

  @Input() OnlyLowerCaseAlphabets: boolean;

  private regex: RegExp = new RegExp( /^[a-z]+$/);

  @HostListener('keydown', [ '$event' ])
  onKeyDown(event: KeyboardEvent) {


    // Do not use event.keycode this is deprecated.
    // See: https://developer.mozilla.org/en-
    // US/docs/Web/API/KeyboardEvent/keyCode
    let current: string = this.el.nativeElement.value;
    // We need this because the current value on the DOM element
    // is not yet updated with the value from this event
    let next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
        event.preventDefault();
    }
   }

}

Here goes the plunker:

https://embed.plnkr.co/M6gYgSxeuw7wW6rfoWEZ/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM