Skip to content
This repository has been archived by the owner on Sep 5, 2023. It is now read-only.

FRONTEND-8638 :: Feature :: Add Custom Angular Validation Patterns #143

Open
wants to merge 2 commits into
base: feature/frontend-2309-remove-getall-putall
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/angular/src/form-validation/form-validators.ts
Original file line number Diff line number Diff line change
@@ -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);
}
}
1 change: 1 addition & 0 deletions packages/angular/src/form-validation/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './form-validators';
1 change: 1 addition & 0 deletions packages/angular/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './data';
export * from './form-validation';
export * from './angular-providers.builder';