1

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 Answers2

0

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]],
Plochie
  • 3,944
  • 1
  • 17
  • 33
  • Create array like `const temp = [Validators.min(-90), Validators.max(90)]` and use that array using spread operator in validators. e.g. `[...temp]` – Plochie Dec 24 '19 at 07:16
  • here is the question https://stackoverflow.com/questions/59465475/store-multiple-validators-into-a-constant-in-angular-8 –  Dec 24 '19 at 07:41
0

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.

timur
  • 14,239
  • 2
  • 11
  • 32
Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42
  • This is fairly straight forward. I see some correct answers on top. So that i shared my view. One thing is important. All the above mentioned answers will do. But if you configure it in endpoint you will not have to go through build processes all over again. For example what if on fly company wants add another Validator. Those will be catered via using configurable endpoint. Otherwise you will have to go to the Front end, add Validator build and deploy. – Selaka Nanayakkara Dec 24 '19 at 06:44
  • yeah, we already using shared service, this can be placed in comments below answer, thanks –  Dec 24 '19 at 06:56