在 Angular 8 Reactive Formbuilder 中存储和使用 Regex Const Validator [英] Store and Use Regex Const Validator in Angular 8 Reactive Formbuilder

查看:23
本文介绍了在 Angular 8 Reactive Formbuilder 中存储和使用 Regex Const Validator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Angular 中存储 Regex 验证器模式以供重用和 Dry 主体?有一个带有正则表达式验证器模式的反应式表单生成器,用于 ZipCode.

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:

ng-pattern 使用来自角度常量的正则表达式

推荐答案

您可以将验证存储在一些 .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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆