Angular UI-Validate without input field(验证表达式)

时间:2015-12-08 07:42:12

标签: javascript angularjs validation ui-validate

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

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

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

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

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

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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>