AngularJS form validation directive for showing input errors

后端 未结 4 2094
我寻月下人不归
我寻月下人不归 2021-02-01 09:12

I need to create a validation directive for showing all input errors for each input automatically. This validation directive should show all errors at current moment and list of

4条回答
  •  一向
    一向 (楼主)
    2021-02-01 09:55

    I want to suggest look at this post in this post author is explaining how to achieve your goals , and you can deeply dive into the code . link

    example from this post showing error messages

    module = angular.module('app', []);
    
    module.directive('showErrors', function($timeout) {
        return {
          restrict: 'A',
          require: '^form',
          link: function (scope, el, attrs, formCtrl) {
            // find the text box element, which has the 'name' attribute
            var inputEl   = el[0].querySelector("[name]");
            // convert the native text box element to an angular element
            var inputNgEl = angular.element(inputEl);
            // get the name on the text box
            var inputName = inputNgEl.attr('name');
    
            // only apply the has-error class after the user leaves the text box
            var blurred = false;
            inputNgEl.bind('blur', function() {
              blurred = true;
              el.toggleClass('has-error', formCtrl[inputName].$invalid);
            });
    
            scope.$watch(function() {
              return formCtrl[inputName].$invalid
            }, function(invalid) {
              // we only want to toggle the has-error class after the blur
              // event or if the control becomes valid
              if (!blurred && invalid) { return }
              el.toggleClass('has-error', invalid);
            });
    
            scope.$on('show-errors-check-validity', function() {
              el.toggleClass('has-error', formCtrl[inputName].$invalid);
            });
    
            scope.$on('show-errors-reset', function() {
              $timeout(function() {
                el.removeClass('has-error');
              }, 0, false);
            });
          }
        }
      });
    
    module.controller('NewUserController', function($scope) {
      $scope.save = function() {
        $scope.$broadcast('show-errors-check-validity');
    
        if ($scope.userForm.$valid) {
          alert('User saved');
          $scope.reset();
        }
      };
    
      $scope.reset = function() {
        $scope.$broadcast('show-errors-reset');
        $scope.user = { name: '', email: '' };
      }
    });
    

提交回复
热议问题