数据绑定数字输入的最小/最大属性时未触发验证 [英] Validation not triggered when data binding a number input's min / max attributes

查看:24
本文介绍了数据绑定数字输入的最小/最大属性时未触发验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多数字输入字段,它们的 min 和 max 属性值取决于我的 AngularJS 应用程序中其他地方的逻辑,但是当在这些属性中使用数据绑定时,Angular 不再验证它们,但是,HTML 5 验证仍然出现去接他们.

var myApp = angular.module('myApp', []);函数 FirstCtrl($scope) {$scope.min = 10;$scope.max = 20;}

<div ng-controller="FirstCtrl"><表单名称="myForm"><input type="number" name="one" required="required"min="10" max="20" ng-model="one"/><input type="number" name="two" required="required"min="{{ min }}" max="{{ max }}" ng-model="two"/><button ng-disabled="!myForm.$valid">提交</button></表单>

直播版本:http://jsfiddle.net/kriswillis/bPUVH/2/

如您所见,验证仍然在 HTML/CSS (Bootstrap) 中处理得很好,因为两个字段在无效时都会变成红色,但是,当第二个字段无效时,提交按钮(由 Angular 处理)不会被禁用.此外,myForm.two.$error 中没有 min 和 max 属性,就像 myForm.one.$error 中一样.

谁能看出我哪里出错了?

解决方案

显然我们不能对 minmax 字段.我查看了源代码,我找到了以下:

if (attr.min) {var min = parseFloat(attr.min);

$interpolate 没有被调用,只是parseFloat,所以你需要指定一个看起来像min 的数字的字符串,并且max.

I have numerous number input fields that have min and max attribute values that depend on logic elsewhere in my AngularJS app, but when using data bindings within these attributes they are no longer validated by Angular, however, the HTML 5 validation still appears to pick them up.

var myApp = angular.module('myApp', []);
function FirstCtrl($scope) {
    $scope.min = 10;
    $scope.max = 20;
}

<div ng-app="myApp">
    <div ng-controller="FirstCtrl">
        <form name="myForm">
            <input type="number" name="one" required="required"
                   min="10" max="20" ng-model="one" />
            <input type="number" name="two" required="required"
                   min="{{ min }}" max="{{ max }}" ng-model="two" />
            <button ng-disabled="!myForm.$valid">Submit</button>
        </form>
    </div>
</div>

Live version: http://jsfiddle.net/kriswillis/bPUVH/2/

As you can see, the validation is still handled fine in the HTML/CSS (Bootstrap) as both fields turn red when invalid, however, the submit button (handled by Angular) is not disabled when the second field is invalid. Also, there are no min and max properties in myForm.two.$error as there are in myForm.one.$error.

Can anyone see where I'm going wrong?

解决方案

Apparently we can't use {{}}s (i.e., interpolation) for the min and max fields. I looked at the source code and I found the following:

if (attr.min) {
  var min = parseFloat(attr.min);

$interpolate is not called, just parseFloat, so you'll need to specify a string that looks like a number for min and max.

这篇关于数据绑定数字输入的最小/最大属性时未触发验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆