两个数字的输入字段验证

时间:2017-07-04 13:53:37

标签: html angularjs

我似乎陷入了输入字段中传递的2个数字的验证问题。我在输入中提供了2个数字,比如num1和num2。 num2必须大于num1。如果不是,那么我需要显示一条错误消息。这是我到目前为止所尝试的。我没有看到错误消息一致显示。如果有人能够指出我可能缺少什么,请欣赏它。

JSFiddle

<input name="num1" type="text" ng-model="num1" placeholder="num1">
<input name="num2" type="text" ng-model="num2" placeholder="num2">
<span ng-show="num1>num2">Num2 cannot be lesser than num1</span>

3 个答案:

答案 0 :(得分:1)

你的小提琴似乎有用,除了可能在num2为空时也显示该消息。将type="text"更改为"type="number"会使其表现得更像您期望的那样。

答案 1 :(得分:0)

您可以使用多种方式

第一个是将输入类型更改为数字

 var app = angular.module("Demo", []);
 app.controller("AppController", function($scope) {

 });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="Demo">
  <div ng-controller="AppController">
    <div ng-form="regForm">
      <input name="num1" type="number" ng-model="num1" placeholder="num1">
      <input name="num2" type="number" ng-model="num2" placeholder="num2">
      <span ng-show="num1>num2">Num2 cannot be lesser than num1</span>
    </div>
  </div>
</div>

另一种方法是将输入用作文本并将控制器函数与ng-show相关联,以便比较整数而不是字符串值

 var app = angular.module("Demo", []);
 app.controller("AppController", function($scope) {
    $scope.checkNum = function(){
      return parseInt($scope.num1) > parseInt($scope.num2) 
 }
 });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="Demo">
  <div ng-controller="AppController">
    <div ng-form="regForm">
      <input name="num1" type="text" ng-model="num1" placeholder="num1">
      <input name="num2" type="text" ng-model="num2" placeholder="num2">
      <span ng-show="checkNum()">Num2 cannot be lesser than num1</span>
    </div>
  </div>
</div>

答案 2 :(得分:0)

将文本框type="text"更改为type="number"

<input name="num1" type="number" ng-model="num1" placeholder="num1">
<input name="num2" type="number" ng-model="num2" placeholder="num2">
<span ng-show="num1 > num2">Num2 cannot be lesser than num1</span>

Demo