1

Im using ui-validate utils https://github.com/angular-ui/ui-validate

The problem is to validate expression on the form without input field. For example? I have an object

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

I would like to receive the error, provided expression: field1 + field2 + field3 == 0

It is common validation for the whole form. Not for some input.

1
  • Please can you add some relevant code also the HTML one? I don't think you need ui-validate for this
    – michelem
    Commented Dec 8, 2015 at 7:54

2 Answers 2

1

You can write a small function like this (not really sure, you need to use ui-validate for this):

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

Now, display it at somewhere in your form:

<form>
    <div ng-show="!validate()">There is some error. Sum can't be zero</div>
    <!-- Your fields below -->
</form>
0

ui-validate can only be used within input tags as there is a requirement for ng-model. ng-show binding to a function would work. Here is an example: 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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.