2

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.

1 Answer 1

1

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.