使用AngularJs进行浮点范围验证 [英] Float range validation using AngularJs

查看:88
本文介绍了使用AngularJs进行浮点范围验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遵循一个基于官方文档的示例来验证float.我的附加要求是浮点值应介于-90到90之间.我添加了最小值和最大值字段,但仍然没有运气.

I am following an example based on official docs to validate float. My added requirement is that float value should lie between -90 to 90. I added the min and max fields but still no luck.

下面是代码:

HTML:

<body ng-app="form-example1">
<form name="form" class="css-form" novalidate>

<div>
  Length (float):
  <input type="text" ng-model="length" name="length"  min="-90" max="90" smart-float />
  {{length}}<br />
  <span ng-show="form.length.$error.float">
    This is not a valid float number!</span>
     <span ng-show="form.length.$error.min || form.length.$error.max">
    The value must be in range -90 to 90!</span>
</div>

JS:

var app = angular.module('form-example1', []);
var FLOAT_REGEXP = /^\-?\d+((\.|\,)\d+)?$/;
app.directive('smartFloat', function() {
return {
  require: 'ngModel',
  link: function(scope, elm, attrs, ctrl) {
    ctrl.$parsers.unshift(function(viewValue) {
      if (FLOAT_REGEXP.test(viewValue)) {
        ctrl.$setValidity('float', true);
        return parseFloat(viewValue.replace(',', '.'));
      } else {
        ctrl.$setValidity('float', false);
        return undefined;
      }
    });
  }
};
});

现在,对最小和最大字段的验证不起作用.允许使用90,但不允许的任何值都更高(例如,不允许90.12345,允许90,允许89.9999,不允许-90.1)

Right now validations for min and max fields are not working. 90 is allowed but anything higher than is not allowed (like 90.12345 is not allowed, 90 is allowed, 89.9999 is allowed, -90.1 is not allowed)

推荐答案

请确保将您的input设置为number类型! min/max验证仅适用于此类型的输入字段.将数字的文档与文本.

Be sure to make your input of type number! The min/max validation is only available for this type of input field. Compare the docs for number to text.

这篇关于使用AngularJs进行浮点范围验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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