简体   繁体   English

角度-通过ng-keydown进行的强制验证未按预期工作

[英]Angular - force validation through ng-keydown is not working as expected

Please see this jsFiddle (Disclaimer - the ng-keydown function isn't calling but that is not the main issue in the fiddle) 请查看此jsFiddle (免责声明-ng-keydown函数未调用,但这不是小提琴中的主要问题)

I am trying to add validation for an input box so numbers (0-100) are allowed and nothing else through a regex I made. 我正在尝试为输入框添加验证,以便允许数字(0-100),而通过我制作的正则表达式则一无所获。 However it is not working as expected as when using this function: 但是,它不能像使用此功能时那样正常工作:

$scope.validatebox = function (e) {

        var element = e.target;
        var element_val = $(element).val();
        element_val = parseInt(element_val);

        var reg = /^[1-9][0-9]?$|^100$/;
        if (reg.test(element_val) === false) //validate
        {
            e.preventDefault();
            return;
        }

    };

The e.preventDefault() acts funny and doesn't permit the user to enter any number if there is nothing in the input box. e.preventDefault()表现有趣,并且如果输入框中没有任何内容,则不允许用户输入任何数字。

How can I ammend my code to force proper validation on the user so he can only enter numbers 0-100. 我如何修改我的代码以强制对用户进行正确的验证,以便他只能输入数字0-100。

AngularJS has support for custom validators, and actually already has some built in for number range. AngularJS支持自定义验证器,实际上已经为数字范围内置了一些验证器。 Instead of writing code to work on keydown, leverage Angular's custom validators. 不用编写代码来进行按键操作,而是利用Angular的自定义验证器。

For numbers in particular, you can use min and max, eg: 特别是对于数字,您可以使用min和max,例如:

<input type="number" name="box1" ng-model="box1"
        min="0" max="100"/>

You just need to put it in a form, and then you can display the error however you wish. 您只需要将其放入表单中,然后可以根据需要显示错误。 Working Fiddle here: http://jsfiddle.net/js4tm3j7/1/ 在这里工作的小提琴: http : //jsfiddle.net/js4tm3j7/1/

More info on number validators here: https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D 有关数字验证器的更多信息,请访问: https : //docs.angularjs.org/api/ng/input/input%5Bnumber%5D

Info on custom validators here: https://docs.angularjs.org/guide/forms 有关自定义验证器的信息,请访问: https//docs.angularjs.org/guide/forms

EDIT 编辑

If you want to force validation instead of just showing an error, take a look at parsers and formatters: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController 如果要强制验证而不只是显示错误,请查看解析器和格式化程序: https : //docs.angularjs.org/api/ng/type/ngModel.NgModelController

There's an example here: filters on ng-model in an input 这里有一个例子: 输入中的ng-model过滤器

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

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