简体   繁体   English

如何使用正则表达式 /^[1-9]\d*$/ 自定义验证两个文本框?

[英]How to custom validate two text boxes with a regular expression /^[1-9]\d*$/?

I'm trying to write a custom validator for 2 text boxes, with some conditions.我正在尝试在某些条件下为 2 个文本框编写自定义验证器。

Please see the code I wrote in Stackblitz Link to validate the text boxes with some conditions请参阅我在Stackblitz Link 中编写的代码,以在某些条件下验证文本框

Kindly help me where did I go wrong.请帮助我 go 哪里错了。

You can add that in textbox1 and textBox2 controls validators您可以在textbox1textBox2控件验证器中添加它

this.registerForm = this.formBuilder.group(
  {
    textbox1: ['', [Validators.required, Validators.pattern("^[1-9]\d*$/"]],
    textbox2: ['', [Validators.required, Validators.pattern("^[1-9]\d*$/"]],
  }
];

Now remove the validator from the formGroup , Validators.pattern will make sure to apply validation on both the field.现在从formGroup中删除验证器, Validators.pattern将确保在两个字段上都应用验证。

Now add errors.pattern inside *ngIf condition to see whether that pattern matched or not.现在在*ngIf条件中添加errors.pattern以查看该模式是否匹配。

<div *ngIf="f.textbox1.errors.pattern">should not start with 0</div>
...
<div *ngIf="f.textbox2.errors.pattern">should not start with 0</div>

Updated Stackblitz 更新了 Stackblitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM