1

我正在使用 ui-validate utils https://github.com/angular-ui/ui-validate

问题是在没有输入字段的表单上验证表达式。例如?我有一个对象

$scope.item = { field1 : 0, field2: 0, field3: 0 };

我想收到错误,提供表达式:field1 + field2 + field3 == 0

这是整个表单的常见验证。不是为了一些输入。

4

2 回答 2

1

您可以编写一个这样的小函数(不太确定,您需要为此使用ui-validate):

$scope.validate = function () {
    var sum = 0;

    // Sum every non Angular key
    angular.forEach($scope.items, function (value, key) {
        // You can also add another check below "angular.isNumber(value)" if you have some text fields
        if (key.charAt(0) !== '$') {
            // Call "parseInt()" method here if values are in string
            sum += value;
        }
    });

    return sum !== 0;
}

现在,将其显示在表单中的某个位置:

<form>
    <div ng-show="!validate()">There is some error. Sum can't be zero</div>
    <!-- Your fields below -->
</form>
于 2015-12-08T07:53:32.880 回答
0

ui-validate 只能在输入标签中使用,因为需要 ng-model。ng-show 绑定到函数会起作用。这是一个例子: http ://codepen.io/ctwoodwa/pen/eJmyYg

angular.module('ngExample', ['ngMessages'])
  .controller('elemController', Controller1);

function Controller1() {
  vm = this;  
  vm.item = { field1 : 0, field2: 0, field3: 0 };
  vm.validate = validate
    
    function validate() {
      // Determine if the form is valid.
      return (vm.item.field1 + vm.item.field2 + vm.item.field3 == 0);
    };
}
<div ng-app='ngExample' ng-controller="elemController as vm">
  <form name="exampleForm">
    <label for="field1">Field1</label>
   <input type="number" name="field1" ng-model="vm.item.field1"/>
    <label for="field2">Field 2</label>
    <input type="number" name="field2" ng-model="vm.item.field2"/>
    <label for="field3">Field 3</label>
    <input type="number" name="field3" ng-model="vm.item.field3"/>
    <div ng-show="vm.validate()">
  <div class="error">This form is not valid</div>
</div>
    <button>Submit</button>
    </form>
</div>

于 2015-12-08T08:22:12.613 回答