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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27212592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:09:09  来源:igfitidea点击:

How to validate input number length with angular?

javascripthtmlangularjs

提问by Elad Noty

I want to validate a 9 digits number using angular,

我想使用 angular 验证一个 9 位数字,

this is in my modal :

这是在我的模式中:

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

i tried pattern = [0-9]{9}, seems its passing every number that its getting . I want to pass only number 000000000 - 9999999999 , min-max also not working for me.

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

this is what my app adding to this class:

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

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

thank u !

感谢你 !

回答by Tom-Oliver Heidel

As mentioned by Rahul Desai you have to use ngMinlength and ngMaxlength.
But since you want to use numbers you have to change the code a little bit to this

正如 Rahul Desai 提到的,你必须使用 ngMinlength 和 ngMaxlength。
但是由于您想使用数字,因此您必须将代码稍微更改为此

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

To be honest I don't know what to do with class="form-control". Maybe you can add it or leave it out?!

老实说,我不知道该怎么办class="form-control"。也许你可以添加它或省略它?!

Anyway you can also try this

无论如何你也可以试试这个

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

You shouldn't need min/max attribute anymore.

你不应该再需要 min/max 属性了。

EDIT:
I guess I made a mistake with the second one. It should be either

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

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

or

或者

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

回答by Rahul Desai

Have you tried both ngMinlengthand ngMaxlengthat the same time?

您是否尝试过两种ngMinlength,并ngMaxlength在同一时间?

Example:

例子:

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

Check out the official documentation regarding this: https://docs.angularjs.org/api/ng/directive/input

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

Very nice tutorial about form validation: http://www.ng-newsletter.com/posts/validations.html

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