问题
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