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
  • I think your pattern is not working try '^\d{1,5}$' instead of /^\d{1,5}$/ Commented Dec 24, 2019 at 6:24
  • yeah, its working on my end, just more curious about saving a regex pattern in variable, and using for later, thanks Commented Dec 24, 2019 at 6:29

2 Answers 2

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]],
Sign up to request clarification or add additional context in comments.

2 Comments

Create array like const temp = [Validators.min(-90), Validators.max(90)] and use that array using spread operator in validators. e.g. [...temp]
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.

2 Comments

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.
yeah, we already using shared service, this can be placed in comments below answer, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.