【问题标题】:How to get Validators to allow white space?如何让验证器允许空白?
【发布时间】: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

标签: html css angular


【解决方案1】:

这是validator 的示例

\s 任意空格

\S 任何非空白字符

【讨论】:

    【解决方案2】:

    这样使用Validators.pattern("^[a-zA-Z ]*$")

    以这种方式使用两个单词之间只允许一个空格 Validators.pattern("^[\w+ ?]*$")

    【讨论】:

    • 您将如何处理标签、返回等?这些都属于 whitespace 的类别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    相关资源
    最近更新 更多