Skip to content

Instantly share code, notes, and snippets.

@Graniron
Created September 16, 2017 18:13
Show Gist options
  • Save Graniron/336bfed75938f8981c9f7008c26e10bb to your computer and use it in GitHub Desktop.
Save Graniron/336bfed75938f8981c9f7008c26e10bb to your computer and use it in GitHub Desktop.
Angular directive for input validation
import { Directive, HostListener, HostBinding } from '@angular/core';
@Directive({
selector: '[credit-card]'
})
export class CreditCardDirective {
@HostBinding('style.border')
border: string;
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
let trimmed = input.value.replace(/\s+/g, '');
if(trimmed.length > 16) {
trimmed = trimmed.substr(0, 16);
}
let numbers = [];
for(let i = 0; i < trimmed.length; i += 4) {
numbers.push(trimmed.substr(i, 4));
}
input.value = numbers.join(' ');
this.border = '';
if(/[^\d]+/.test(trimmed)) {
this.border = '1px solid red';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment