You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FormControl中使用Service.ts中初始化的正则表达式变量

在FormControl中使用service里的正则变量

首先你要注意,当前validationAR是字符串格式的正则表达式(带前后斜杠),而Angular的Validators.pattern()需要的是RegExp实例或者不带前后斜杠的正则字符串,所以得先做适配处理:

方法1:直接修正service里的变量类型

把service里的定义改成真正的RegExp对象,后续使用更直接:

// service.ts
validationAR: RegExp = /^([0-9\s@,.=%$#&_\u0600-\u06FF])+$/;

然后在组件中注入该service,创建FormControl时直接传入正则:

// 组件.ts
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { YourService } from './path/to/service.ts';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html'
})
export class YourComponent {
  constructor(private yourService: YourService) {}

  // 创建带验证规则的FormControl
  myControl = new FormControl('', [
    Validators.pattern(this.yourService.validationAR)
  ]);
}

方法2:保留原service变量格式的适配方案

如果必须保留字符串格式的正则,在组件里使用时需要先把字符串转换成RegExp实例:

// 组件.ts
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { YourService } from './path/to/service.ts';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html'
})
export class YourComponent {
  constructor(private yourService: YourService) {}

  // 处理字符串正则:移除前后的/,生成RegExp实例
  get convertedRegex(): RegExp {
    const pureRegexStr = this.yourService.validationAR.replace(/^\/|\/$/g, '');
    return new RegExp(pureRegexStr);
  }

  // 创建FormControl
  myControl = new FormControl('', [
    Validators.pattern(this.convertedRegex)
  ]);
}

补充说明:Validators.pattern()也支持传入不带前后斜杠的正则字符串,所以如果把service里的变量改成"^([0-9\s@,.=%$#&_\u0600-\u06FF])+$"这种格式,也可以直接传给验证器,但使用RegExp实例是更稳妥的方式。

内容的提问来源于stack exchange,提问作者Haris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 08:40:42