1
votes

How do I store a Regex Validator pattern for reuse and Dry principal in Angular? Have a reactive formbuilder with Regex validator pattern below for ZipCode.

Need to apply to multiple address forms, curious how to save /^\d{1,5}$/

So we can write Validators.pattern(zipcode), or any syntax utilized in Angular? Company has more complicated long patterns for phone numbers, customer number, etc.

'ZipCode': [null, [Validators.maxLength(16), Validators.pattern(/^\d{1,5}$/)]],

Looking for a way to store and utilize maybe in constants.

This is for Angular 2:

ng-pattern to use regex from angular constants

2
I think your pattern is not working try '^\d{1,5}$' instead of /^\d{1,5}$/ - Ashot Aleqsanyan
yeah, its working on my end, just more curious about saving a regex pattern in variable, and using for later, thanks - user12555362

2 Answers

0
votes

You can store your validations in some .ts files, suppose validations.ts.

Then use these validations wherever required. You can also have parameter Validators.

validation.ts

export const ZipValidation = Validators.pattern(/^\d{1,5}$/);
export const EmailValidation = Validators.pattern(/*some regex*/);
export const UsernameValidation = Validators.pattern(/*some regex*/);
export const ValidWithParam = (param: number) => {
  return Validators.pattern('/\d' + param + '/g');
}

In Component

import { ZipValidation, EmailValidation, UsernameValidation } from './validation';
'ZipCode': [null, [Validators.maxLength(16), ZipValidation]],
0
votes

Best thing is to have a main root-level shared service and store all the patterns inside it.

Whenever you need it - you can use it by referring to the shared service. And via that particular service if you can implement a endpoint(if possible) so that it will be possible to configure the Validators via your application backend.

Otherwise you can hardcode the Validators patterns in the service itself.