diff --git a/packages/angular/src/form-validation/form-validators.ts b/packages/angular/src/form-validation/form-validators.ts new file mode 100644 index 0000000..641c43e --- /dev/null +++ b/packages/angular/src/form-validation/form-validators.ts @@ -0,0 +1,45 @@ +import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; + +export class FormValidators { + private static readonly ERROR_BODY = { valid: false }; + + /** + * Substitution of the native `Validations.pattern` that allows + * an id as an input so multiple patterns can be used and identified. + * It also allows a string pattern or a RegExp. + */ + public static pattern(pattern: RegExp | string, id = 'pattern'): ValidatorFn { + return (control: AbstractControl): ValidationErrors | null => { + return FormValidators.isPatternFound(control, pattern) + ? null + : { + [id]: FormValidators.ERROR_BODY, + }; + }; + } + + /** + * Unlike "pattern" validator, "errorPattern" uses the pattern + * to identify the errors in the FormControl value. + */ + public static errorPattern(pattern: RegExp | string, id = 'errorPattern'): ValidatorFn { + return (control: AbstractControl): ValidationErrors | null => { + return FormValidators.isPatternFound(control, pattern) + ? { + [id]: FormValidators.ERROR_BODY, + } + : null; + }; + } + + private static isPatternFound(control: AbstractControl, pattern: RegExp | string): boolean { + const value = control.value; + if (!value) { + return false; + } + + const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern; + + return regex.test(value); + } +} diff --git a/packages/angular/src/form-validation/index.ts b/packages/angular/src/form-validation/index.ts new file mode 100644 index 0000000..2e9235a --- /dev/null +++ b/packages/angular/src/form-validation/index.ts @@ -0,0 +1 @@ +export * from './form-validators'; diff --git a/packages/angular/src/index.ts b/packages/angular/src/index.ts index c63ecc3..a9fadbd 100644 --- a/packages/angular/src/index.ts +++ b/packages/angular/src/index.ts @@ -1,2 +1,3 @@ export * from './data'; +export * from './form-validation'; export * from './angular-providers.builder';