regex - Angular 7 中的模式验证

标签 regex typescript angular7

我的 Angular 7 表单中有一个联系电话字段。我使用“form builder”和“validators.pattern”进行验证。在 HTML 中,我尝试了两种方法来确定是否有一个错误,但两者都不起作用。

typescript : mobnumPattern = "^[6-9][0-9]{9}$"; this.myForm = this.formbuilder.group({ contact_no: ['', [Validators.required,Validators.pattern(this.mobnumPattern)]],} )

1.当我使用下面的HTML时,验证总是显示true

*ngIf="((myForm.controls['contact_no'].touched) && (myForm.controls['contact_no'].hasError(pattern)))"

2.当我使用下面的HTML时,验证总是显示错误

*ngIf="((myForm.controls['contact_no'].touched) && (myForm.controls['contact_no'].errors.pattern))"

知道如何解决这个问题吗?

提前致谢。

最佳答案

让我们回顾一下您提到的两种情况。

1.When I used below HTML, validation always shows true

我尝试在 stackblitz 中重现该问题,但与您所说的不同,它总是错误的。无论如何,检查 myForm.controls['contact_no'].hasError(pattern) 返回 false,因为 hasError()expecting a string as its parameter,但这里的模式未定义。

使用它来检查表单控件是否存在模式验证错误。

*ngIf="((myForm.controls['contact_no'].touched)&& myForm.controls['contact_no'].hasError('pattern')))"

2.When I used below HTML, validation always shows false

如果表单控件没有任何验证错误,

myForm.controls['contact_no'].errors 将为 null。因此,在模板中检查 myForm.controls['contact_no'].errors.pattern 时会抛出错误并返回 undefined。如果 myForm.controls['contact_no'].errors 为 null,请使用安全导航运算符来防止 View 渲染失败。

像这样:

*ngIf="((myForm.controls['contact_no'].touched) && (myForm.controls['contact_no'].errors?.pattern)"

我做了一个stackblitz通过上述修复。检查链接以查看工作演示。

关于regex - Angular 7 中的模式验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53882658/

相关文章:

python - 正则表达式:如何从字符串中提取第一个 IP 地址(在 Python 中)

c# - 正则表达式删除特殊/不可见字符

debugging - Webpack 捆绑的 Node 或 Electron 主进程的 VSCode 调试

angular - 使用 index.html 离线运行 Angular 7 Web 应用程序

regex - 正则表达式代码

node.js - 如何在 NodeJS 中使用只有 URL 的 Sharp 调整图像大小,使用 async/await,并且没有创建本地副本?

javascript - Amcharts 4 获取嵌套数组数据

javascript - 通过@Input()传递的数据

angular - Angular 的路由,具有某些功能模块的通用布局

Python正则表达式拆分函数多个分隔符