在Angular 8 Reactive Formbuilder中存储和使用Regex Const Validator [英] Store and Use Regex Const Validator in Angular 8 Reactive Formbuilder
问题描述
如何在Angular中存储正则表达式验证器模式以供重用和Dry主体使用? 在ZipCode的下面有一个具有Regex验证器模式的反应式formbuilder.
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.
需要应用于多个地址表格,好奇如何保存/^\d{1,5}$/
Need to apply to multiple address forms, curious how to save /^\d{1,5}$/
因此我们可以编写Validators.pattern(zipcode)
或Angular中使用的任何语法?
公司在电话号码,客户号码等方面有更复杂的长模式.
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.
这是针对Angular 2的:
This is for Angular 2:
推荐答案
您可以将验证存储在某些.ts
文件中,假设是validations.ts
.
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');
}
在组件中
import { ZipValidation, EmailValidation, UsernameValidation } from './validation';
'ZipCode': [null, [Validators.maxLength(16), ZipValidation]],
这篇关于在Angular 8 Reactive Formbuilder中存储和使用Regex Const Validator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!