user1424508
user1424508

Reputation: 3301

AngularJS Validation

Hi I want to create a custom directive to do form validation. I have a form with checkboxes and some text fields. I want to make sure the user doesn't leave any of the fields empty.

When the user leaves a form empty after pressing submit, I want the directive to highlight the border of the field red. My problem is that when I make an isolate scope directive it doesn't work. When it isn't an isolate scope, all the fields turn red when only one is empty. How can I fix this?

directive.js:

   directive('createprofileformerrormsg', function() {
     return {
              scope:{createprofileformerrormsg:'@'},
    restrict: 'A',
               require: 'ngModel',
    link: function(scope, elem, attr, ngModel) {

        scope.$watch('formErrors', function() {

            if (attr.createprofileformerrormsg == 1) {

                elem.css("border", "red solid 1px");
            }
        });

    }


}
});

form.html

 <form data-ng-submit="createProfile()">
  Ethnicity:  <select createprofileformerrormsg="{{formErrors.ethnicity}}" data-ng-   

 model="ethnicity"  >
    <option value="Asian">Asian</option>
    <option value="Black">Black</option>
    <option value="Caucasian">Caucasian</option>
    <option value="Hispanic">Hispanic</option>
    <option value="Middle Eastern">Middle Eastern</option>
    <option value="Native American">Native American</option>
    <option value="Other ethnicities">Other ethnicities</option>

</select><br/>
Gender:  <select createprofileformerrormsg="formErrors.ethnicity" data-ng-

model="gender">
    <option value="Male">Male</option>
    <option value="Female">Female</option>
</select>
</form>

Controller.js

  $scope.createProfile = function() {
 if ($scope.ethnicity == null) {
        $scope.formErrors.ethnicity = 1;
        error_count++;
    }
  if ($scope.gender == null) {
        $scope.formErrors.ethnicity = 1;
        error_count++;
    }
}

Upvotes: 0

Views: 383

Answers (1)

Michael Benford
Michael Benford

Reputation: 14114

Try this:

Javascript

app.controller('MainCtrl', function($scope) {      
  $scope.submit = function() {
    $scope.$broadcast('submit');
  }
})
.directive('highlightOnError', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      scope.$on('submit', function() {
        var border = '';
        if (ngModel.$invalid)
          border = 'red solid 1px';

        element.css('border', border);
      });
    }
  };
});

HTML

<body ng-controller="MainCtrl">
  <form ng-submit="submit()" novalidate>
    <input type="text" ng-model="foo" required highlight-on-error />
    <select ng-model="bar" ng-options="option for option in [1, 2, 3]" 
       required highlight-on-error>
      <option value="">choose a number</option>
    </select>
    <button type="submit">Submit</button>
  </form>
</body>

Working Plunker here.

Upvotes: 1

Related Questions