0

I was trying to follow some tutorials, but couldn't figure out what to do.

I would like to add the validation, that at least one of the checkboxes (consumer/vendor) has to be true. If not true show an error message at both fields). What would be the easiest way to accomplish that?

<form role="form" name="addClientForm" ng-submit="submitForm(addClientForm.$valid)" novalidate>
        <div class="form-group" ng-class="{ 'has-error' : addClientForm.title.$invalid && !addClientForm.title.$pristine }">
            <label>Title</label>
            <input type="text" class="form-control" placeholder="Enter a title" ng-model="client.title" required>
        </div>
        <div class="form-group" ng-class="{ 'has-error' : addClientForm.company.$invalid && !addClientForm.company.$pristine }">
            <label>Company</label>
            <input type="text" class="form-control" placeholder="Enter a company" ng-model="client.company" required>
        </div>
        <div class="checkbox">
          <label class="i-checks">
            <input type="checkbox" ng-model="client.consumer"><i></i> Consumer
          </label>
        </div>
        <div class="checkbox">
          <label class="i-checks">
            <input type="checkbox" ng-model="client.vendor"><i></i> Vendor
          </label>
        </div>
    </form>

Controller (modal controller)

angular.module('App')
  .controller('ModalAddClientCtrl', function ($scope, $modalInstance) {

    $scope.client = { title: '', company: '', consumer: true, vendor: false };

    $scope.submitForm = function(isValid) {

    };

    $scope.ok = function () {

      $modalInstance.close($scope.client);

    };

    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };
  });
Tino
  • 3,340
  • 5
  • 44
  • 74

1 Answers1

0

To use angular form validation like you are trying to you have to set name attribute in the input fields. So, if you have a <form name='form'> with <input name='input'> only then you can use form.input.$dirty or form.input.$pristine. Combine that with ng-if like you have the rest is simple.

See this fiddle for example and try editing the values. I have implemented validation in your form. I have left out the controller, conditions and error messages could be simpler but you will get the idea.

See this related post that has an excellent answer on using form validation.

Community
  • 1
  • 1
mxp
  • 180
  • 6