Regex angular 7中的模式验证
我在Angular 7表单中有一个联系人号码字段。我使用“form builder”和“validators.pattern”进行验证。在HTML中,我尝试了两种方法来确定是否存在错误,但都不起作用 打字稿: mobnumPattern=^[6-9][0-9]{9}$; this.myForm=this.formbuilder.group{ 联系方式:[,[Validators.required,Validators.patternthis.mobnumPattern]],} 1.当我使用下面的HTML时,验证总是显示trueRegex angular 7中的模式验证,regex,typescript,angular7,Regex,Typescript,Angular7,我在Angular 7表单中有一个联系人号码字段。我使用“form builder”和“validators.pattern”进行验证。在HTML中,我尝试了两种方法来确定是否存在错误,但都不起作用 打字稿: mobnumPattern=^[6-9][0-9]{9}$; this.myForm=this.formbuilder.group{ 联系方式:[,[Validators.required,Validators.patternthis.mobnumPattern]],} 1.当我使用下面
*ngIf="((myForm.controls['contact_no'].touched) && (myForm.controls['contact_no'].hasError(pattern)))"
2.当我使用下面的HTML时,验证总是显示false
*ngIf="((myForm.controls['contact_no'].touched) && (myForm.controls['contact_no'].errors.pattern))"
你知道怎么解决这个问题吗
提前谢谢。我们来看看你提到的两个案例 1.当我使用下面的HTML时,验证总是显示true
*ngIf="((myForm.controls['contact_no'].touched) && (myForm.controls['contact_no'].hasError(pattern)))"
我试着在stackblitz中重现这个问题,但与你所说的不同,它总是错误的。无论如何,check myForm.controls['contact_no'].hasErrorpattern返回false,因为hasError为,但此处的模式未定义
使用此选项检查表单控件是否存在模式验证错误
*ngIf="((myForm.controls['contact_no'].touched)&& myForm.controls['contact_no'].hasError('pattern')))"
2.当我使用下面的HTML时,验证总是显示false
*ngIf="((myForm.controls['contact_no'].touched) && (myForm.controls['contact_no'].errors.pattern))"
myForm.controls['contact_no']。如果表单控件没有任何验证错误,则错误将为null。因此,在检查myForm.controls['contact_no'].errors.pattern时,模板中的会抛出错误并返回undefined。如果myForm.controls['contact_no']错误为空,请使用安全导航操作符防止视图渲染失败
像这样:
*ngIf="((myForm.controls['contact_no'].touched) && (myForm.controls['contact_no'].errors?.pattern)"
我已对上述修复进行了修改。查看链接以查看正在运行的演示