Skip to content

Instantly share code, notes, and snippets.

@gildniy
Created December 12, 2017 03:00
Show Gist options
  • Save gildniy/09fec577b766d57aa56cab692781047d to your computer and use it in GitHub Desktop.
Save gildniy/09fec577b766d57aa56cab692781047d to your computer and use it in GitHub Desktop.
Angular 4 validation service
import { Injectable } from '@angular/core';
import { AbstractControl } from '@angular/forms';
// TODO: Check these: https://auth0.com/blog/angular2-series-forms-and-custom-validation/
@Injectable()
export class ValidationService {
static getValidatorErrorMessage(validatorName: string, validatorValue?: any) {
let config = {
'required': 'Required',
'invalidCreditCard': 'Is invalid credit card number',
'invalidEmailAddress': 'Invalid email address',
'invalidPassword': 'Invalid password. Password must be at least 6 characters long, and contain a number.',
'invalidNationalId': 'Invalid Rwanda National ID number.',
'minlength': `Minimum length ${validatorValue.requiredLength}`,
'maxlength': `Maximum length ${validatorValue.requiredLength}`
};
return config[validatorName];
}
static creditCardValidator(control) {
// Visa, MasterCard, American Express, Diners Club, Discover, JCB
if (control.value.match(/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/)) {
return null;
} else {
return { 'invalidCreditCard': true };
}
}
static emailValidator(control) {
// RFC 2822 compliant regex
if (control.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/)) {
return null;
} else {
return { 'invalidEmailAddress': true };
}
}
static passwordValidator(control) {
// {6,100} - Assert password is between 6 and 100 characters
// (?=.*[0-9]) - Assert a string has at least one number
if (control.value.match(/^(?=.*[0-9])[a-zA-Z0-9!@#$%^&*]{6,100}$/)) {
return null;
} else {
return { 'invalidPassword': true };
}
}
static nationalIdValidator(control) {
// 1 - Assert national-id begins with number 1
// (19[0-9]{2}|20[0-9]{2}|2100) - Assert national-id has on the 2nd to the 4th position a number between 1900 and 2100
// ([78])0 - Assert national-id has on the 5th position either number 7 or 8 followed by mumber 0
// \d{9} - Assert national-id ends with a set of 9 digits
// 1 1900 7 0000000 0 00 -> 1 2100 8 0999999 9 99 (All IDs between this set are allowed)
if (control.value.match(/^1(19[0-9]{2}|20[0-9]{2}|2100)([78])0\d{9}$/)) {
return null;
} else {
return { 'invalidNationalId': true };
}
}
public minLengthArray(min: number) {
return (c: AbstractControl): { [key: string]: any } => {
if (c.value.length >= min)
return null;
return { 'minLengthArray': { valid: false } };
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment