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

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

问题描述

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

代码如下:

HTML:

<form name="form" class="css-form" novalidate><div>长度(浮动):<input type="text" ng-model="length" name="length" min="-90" max="90" smart-float/>{{长度}}<br/><span ng-show="form.length.$error.float">这不是有效的浮点数!</span><span ng-show="form.length.$error.min || form.length.$error.max">该值必须在 -90 到 90 的范围内!</span>

JS:

var app = angular.module('form-example1', []);var FLOAT_REGEXP =/^\-?\d+((\.|\,)\d+)?$/;app.directive('smartFloat', function() {返回 {要求:'ngModel',链接:函数(范围,榆树,属性,ctrl){ctrl.$parsers.unshift(function(viewValue) {如果(FLOAT_REGEXP.test(viewValue)){ctrl.$setValidity('float', true);返回 parseFloat(viewValue.replace(',', '.'));} 别的 {ctrl.$setValidity('float', false);返回未定义;}});}};});

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

解决方案

请务必使您的 input 类型为 numbermin/max 验证仅适用于此类输入字段.将 number 的文档与 text.

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.

Below is the code:

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;
      }
    });
  }
};
});

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)

解决方案

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天全站免登陆