angular - Angular 7:Formvalidation,Validators.pattern 不起作用
问题描述
我需要一个来自仅匹配整数的验证。因此我使用pattern
带有正则表达式的验证器(见下文)。此外,该字段不应为空,因此我添加了required
验证器。
但是pattern
永远不会触发错误。我阅读了角度文档并查看了源代码,pattern
但对我来说仍然没有意义。此外,我已经阅读了与该主题相关的几乎所有关于 stackoverflow 的问题。但我仍然无法弄清楚为什么该模式不起作用。
或许有人能帮帮我,谢谢!
这是我的代码component.ts:
// definition of the formcontrol
hours = new FormControl('', [
Validators.required,
Validators.pattern('^[0-9]*$'),
])
// for debugging
log() {
console.log('required: ', this.hours.hasError('required'));
console.log('pattern: ', this.hours.hasError('pattern'));
console.log('Erros: ', this.hours.errors);
}
模板:
<mat-form-field>
<input matInput [formControl]="hours" (input)="log()"
placeholder="Anzahl der ausbezahlten Überstunden" type="number">
<mat-error *ngIf="hours.hasError('required') && !hours.hasError('pattern')">
Anzahl der Überstunden fehlt!
</mat-error>
<mat-error *ngIf="!hours.hasError('required') && hours.hasError('pattern')">
Anzahl muss eine Ganzzahl sein!
</mat-error>
</mat-form-field>
例子inputValue=""
:
required: true
pattern: false
Error: Object { required: true }
inputValue="1"
:
required: false
pattern: false
Error: null
inputValue="a"
:
required: true
pattern: false
Error: Object { required: true }
解决方案
它不适用于 type="number",如果将其更改为 type="text" 它将起作用
推荐阅读
- apache - Apache 和 IBM WAS,was_ap24_module 仅用于指定
可能的? - c# - window.location.replace(); is not redirecting the page on button click
- docker - 工作节点上的 NFS 服务器无法访问
- python - 为什么我无法导入此 CSV 文件?
- intellij-idea - Intellij IDEA:使用密码在远程服务器上通过 SSH 构建、scp 和调用脚本
- sass - 如何将地图映射(转换)为具有修改的键和值的新地图
- terraform - Terraform 重用配置块
- html - 测试代码笔的问题
- java - 如何使用 spock 框架测试没有 args 的方法
- java - 我可以使用变量作为通用指标吗?