Skip to content

Instantly share code, notes, and snippets.

@ihorbond
Last active July 20, 2018 22:39
Show Gist options
  • Save ihorbond/2fc7a2653fa5585042955fe8bfd88b08 to your computer and use it in GitHub Desktop.
Save ihorbond/2fc7a2653fa5585042955fe8bfd88b08 to your computer and use it in GitHub Desktop.
Angular FormControl ZipCode Directive for North America
import { Directive, ElementRef, Input, HostListener} from '@angular/core';
import { NgControl, ValidationErrors } from '@angular/forms';
/*
* Directive to format zip codes on FormControl
*/
@Directive({
selector: '[zipCode]'
})
export class ZipCodeDirective {
@Input('country')
public country: CountryEnum = CountryEnum.USA;
protected hyphenKeyCode: number = 189;
protected backSpaceKeyCode: number = 8;
constructor(protected el: ElementRef, protected ngControl: NgControl) { }
@HostListener('keyup', ['$event'])
protected onkeyup(event): void {
const keyCode: number = event.keyCode;
let value: string = this.ngControl.control.value;
if (!value || value.length === 0 || keyCode === this.backSpaceKeyCode) return;
value.toString().trim();
switch (this.country) {
case CountryEnum.USA:
if (!(keyCode === this.hyphenKeyCode && value.length === 6))
value = value.replace(/[^0-9]/g, '');
if (value.length > 9)
value = value.slice(0, 9);
if (value.length > 5 && value[5] !== '-')
value = value.slice(0, 5) + "-" + value.slice(5);
break;
case CountryEnum.CAN:
value = value.toUpperCase();
break;
}
this.el.nativeElement.value = value;
this.ngControl.control.setValue(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment