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
Changes from 1 commit
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.
*/
private static pattern(pattern: RegExp | string, id = 'pattern'): ValidatorFn {
orioljp marked this conversation as resolved.
Show resolved Hide resolved
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.
*/
private 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);
}
}