AngularJS form validation directive for showing input errors

后端 未结 4 2096
我寻月下人不归
我寻月下人不归 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

    Here is the pattern that I used (with Angular 1.3):

    app.directive('number', function() {
      var NUMBER_REGEXP = /^(\d+)$/;
      return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
          ctrl.$validators.number = function(modelValue, viewValue) {
            return NUMBER_REGEXP.test(viewValue);
          };
        }
      };
    });
    

    Then I was able to check for errors in the HTML (with Bootstrap 3.3) using this pattern:

    Please enter a number

    Explanation:

    The number attribute in the tag triggers the directive, which causes the ngModel validator 'number' to be called and to set/unset value.$error.number.

    If value.$error.number is set, then the has-error class is applied to the form-group so it displays a red input field and the help message is displayed.

提交回复
热议问题