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

如何在Angular中编写pattern与正则表达式实现指定格式输入校验

Angular 输入框自定义正则pattern实现方案

你需要的正则可直接匹配要求的三类格式,表达式为 ^(?:"[a-zA-Z\s]+"|[a-zA-Z]+,)$,匹配规则如下:

  • 匹配双引号包裹的纯英文+空格内容,覆盖 "Demo"、"Demo Data" 两类场景
  • 匹配无引号、末尾带英文逗号的纯英文内容,覆盖 Demo, 场景
  • 自动拦截引号不配对、逗号位置错误、含额外特殊字符的非法输入

模板驱动表单用法

直接在input标签绑定pattern属性即可,示例代码:

<input 
  type="text" 
  name="validateInput" 
  ngModel 
  pattern='^(?:"[a-zA-Z\s]+"|[a-zA-Z]+,)$'
  #validateInput="ngModel"
>
<!-- 错误提示 -->
<div *ngIf="validateInput.invalid && (validateInput.dirty || validateInput.touched)">
  输入格式有误,请输入双引号包裹的英文内容,或是英文单词加英文逗号结尾的内容
</div>

响应式表单用法

先在组件类中定义校验规则,再绑定到模板即可:

组件ts代码

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-custom-input',
  templateUrl: './custom-input.component.html'
})
export class CustomInputComponent {
  inputForm: FormGroup;
  // 自定义正则规则
  private inputRule = /^(?:"[a-zA-Z\s]+"|[a-zA-Z]+,)$/;

  constructor(private fb: FormBuilder) {
    this.inputForm = this.fb.group({
      content: ['', [Validators.required, Validators.pattern(this.inputRule)]]
    });
  }
}

对应模板代码

<form [formGroup]="inputForm">
  <input type="text" formControlName="content">
  <!-- 错误提示 -->
  <div *ngIf="inputForm.get('content')?.invalid && (inputForm.get('content')?.dirty || inputForm.get('content')?.touched)">
    输入格式有误,请输入双引号包裹的英文内容,或是英文单词加英文逗号结尾的内容
  </div>
</form>

提示:如果需要支持引号内包含数字、其他特殊字符,可自行调整正则中括号内的匹配规则,比如需要支持数字就把[a-zA-Z\s]改成[a-zA-Z0-9\s]即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 01:15:00