Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

What's the angular way to add validation rules to a form, that do not belong to a single input field, but on multiple field values together?

E.g.:

  • Check if at least one of x checkboxes is checked
  • Check if the sum of multiple number inputs is equal to a given Number
  • ...

It would be nice if the errors can be shown with ng-messages. I'm using angular 1.3.10.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

There's no built-in functionality, but it requires little effort.

ng-messages does not depend on anything specific. It just needs an object whose keys can be referenced by ng-message. The simplest solution would be to hook into the submit event (which you probably do anyway) and run additional validation.

<form ng-submit="post()" name="myForm">
  <input type="checkbox" name="one" ng-model="one" />
  <input type="checkbox" name="two" ng-model="two" />
  <input type="submit" />
  <div ng-messages="formErrors">
    <p ng-message="tooMany">Please, check one checkbox only</p>
    <p ng-message="required">Please, check a checkbox</p>
  </div>
</form>

On submission the function post() is called which adds any error to the object formErrors:

$scope.post = function() {
  ...
  var hasErrors = false;
  $scope.formErrors = {
  };

  if ($scope.one && $scope.two) {
    $scope.formErrors.tooMany = hasErrors = true;
  }

  if (!$scope.one && !$scope.two) {
    $scope.formErrors.required hasErrors = true;
  }

  if (hasErrors) {
     return;
  }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.