【发布时间】:2019-09-04 04:04:17
【问题描述】:
问题是当我在文本输入中添加空格时,我的 Angular 代码会在表单控件上触发错误。我希望正则表达式允许空格。我尝试了几种不同的正则表达式模式。我相信我目前使用的应该是允许字母和空格。
TypeScript
form = this.fb.group({
title: [,[Validators.required,Validators.pattern("[a-zA-Z\s]+")]],
author: [,[Validators.required,Validators.pattern('/^[a-zA-Z\s]*$/')]],
description: [,Validators.required],
date: [new Date]
})
HTML
<div class="form-group">
<label for="title"> Article Title </label>
<span
style="color: red;font-style: italic"
*ngIf="(mouseOverSubmit || form.controls.title?.touched)
&& form.controls.title?.errors?.required">
Required
</span>
<span
style = "color:red;font-style: italic"
*ngIf= "form.controls.title?.touched
&& form.controls.title?.errors?.pattern">
Only letters and numbers allowed
</span>
<input (ngModel)="title"
name="title"
formControlName="title"
class="form-control"
type="text"
id="title">
</div>
【问题讨论】:
-
我确定您需要转义模式中的反斜杠,因为它在字符串中。尝试将
\s更改为\\s。