Created
September 16, 2017 18:13
-
-
Save Graniron/336bfed75938f8981c9f7008c26e10bb to your computer and use it in GitHub Desktop.
Angular directive for input validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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