From 0c59027a1ff3757ee644e8cfb06517b914644352 Mon Sep 17 00:00:00 2001 From: Mike Phillips Date: Wed, 11 Dec 2019 14:48:21 -0500 Subject: [PATCH] feat: specify expiration date digits --- src/credit-card.validator.ts | 55 ++++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/src/credit-card.validator.ts b/src/credit-card.validator.ts index 9e8b3dc..6208ede 100644 --- a/src/credit-card.validator.ts +++ b/src/credit-card.validator.ts @@ -1,4 +1,4 @@ -import { AbstractControl, ValidationErrors, Validators } from '@angular/forms'; +import { AbstractControl, ValidationErrors, ValidatorFn, Validators } from '@angular/forms'; import { CreditCard } from './shared/credit-card'; export class CreditCardValidator { @@ -34,37 +34,44 @@ export class CreditCardValidator { return {'ccNumber': true}; } - static validateExpDate(control: AbstractControl): ValidationErrors|null { - if (Validators.required(control) !== undefined && Validators.required(control) !== null) { - return {'expDate': true }; - } + static validateExpDate(options?: { yearDigits: 2 | 4 }): ValidatorFn { + return (control: AbstractControl): ValidationErrors|null => { + if (Validators.required(control) !== undefined && Validators.required(control) !== null) { + return {'expDate': true }; + } - if (typeof control.value !== 'undefined' && control.value.length >= 5) { - let [month, year] = control.value.split(/[\s\/]+/, 2), + if (typeof control.value !== 'undefined' && control.value.length >= 5) { + let [month, year] = control.value.split(/[\s\/]+/, 2), prefix; - if ((year != null ? year.length : void 0) === 2 && /^\d+$/.test(year)) { - prefix = new Date().getFullYear(); - prefix = prefix.toString().slice(0, 2); - year = prefix + year; - } - month = parseInt(month, 10).toString(); - year = parseInt(year, 10).toString(); + if ((year != null ? year.length : void 0) === 2 && /^\d+$/.test(year)) { + if (options && options.yearDigits && options.yearDigits === 4) { + return {'expDate': true }; + } + prefix = new Date().getFullYear(); + prefix = prefix.toString().slice(0, 2); + year = prefix + year; + } else if (options && options.yearDigits && options.yearDigits === 2) { + return {'expDate': true}; + } + month = parseInt(month, 10).toString(); + year = parseInt(year, 10).toString(); - if (/^\d+$/.test(month) && /^\d+$/.test(year) && (month >= 1 && month <= 12)) { - let currentTime, expiry; - expiry = new Date(year, month); - currentTime = new Date(); - expiry.setMonth(expiry.getMonth() - 1); - expiry.setMonth(expiry.getMonth() + 1, 1); + if (/^\d+$/.test(month) && /^\d+$/.test(year) && (month >= 1 && month <= 12)) { + let currentTime, expiry; + expiry = new Date(year, month); + currentTime = new Date(); + expiry.setMonth(expiry.getMonth() - 1); + expiry.setMonth(expiry.getMonth() + 1, 1); - if (expiry > currentTime) { - return null; + if (expiry > currentTime) { + return null; + } } } - } - return {'expDate': true }; + return {'expDate': true }; + }; } }