Store and Use Regex Const Validator in Angular 8 Reactive Formbuilder

拥有回忆 提交于 2020-01-05 07:13:36

问题


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


回答1:


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]],



回答2:


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.



来源:https://stackoverflow.com/questions/59464574/store-and-use-regex-const-validator-in-angular-8-reactive-formbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!