如何使用角度验证输入数字长度

How to validate input number length with angular?

本文关键字:数字 字长 输入 验证 何使用      更新时间:2023-09-26

我想用角度验证一个 9 位数字,

这是我的模态:

<input type="number" class="form-control" ng-model="id" required>

我尝试了模式= [0-9]{9},似乎它传递了它得到的每个数字。我只想传递数字 000000000 - 9999999999,最小-最大也不适合我。

这是我的应用程序添加到此类的内容:

 class="form-control ng-pristine ng-valid-number ng-invalid ng-invalid-required"

谢谢!

我只是使用pattern作为验证器。以下代码将使字段required,并且必须only digits长度10

ngOnInit() {
    this.firstForm = this.fb.group({
        firstCtrl: ['', [Validators.pattern('^[0-9]{10}$'), Validators.required]],
    });

您是否同时尝试过ngMinlengthngMaxlength

例:

<input type="text" ng-minlength=9 ng-maxlength=9 />

查看有关此的官方文档:https://docs.angularjs.org/api/ng/directive/input

关于表单验证的非常好的教程:http://www.ng-newsletter.com/posts/validations.html

正如Rahul Desai提到的,你必须使用ngMinlength和ngMaxlength。
但是由于你想使用数字,你必须将代码稍微改变一下

<input type="number" ng-model="id" ng-minlength=9 ng-maxlength=9 required />

老实说,我不知道如何处理class="form-control".也许您可以添加它或省略它?!

反正你也可以试试这个

<input type="number" ng-model="id" ng-pattern="/^[0-9]{1,9}$/" required />

您不再需要最小/最大属性。

编辑:
我想我在第二个上犯了一个错误。它应该是

ng-pattern="/^[0-9]{9}$/"

ng-pattern="/^[0-9]{9,9}$/"

使用响应式表单,您应该以这样的方式编写验证器:

formControlYourField: [
  "",
  Validators.compose([
    Validators.required,
    Validators.minLength(9),
    Validators.maxLength(9),
    Validators.pattern("^[0-9]*$"),
  ]),
]

当然还有你的.html

<input
  matInput
  required
  formControlName="formControlYourField"
  type="text"
  placeholder="123456789"
/>