如何为角度组件添加自定义验证?

时间:2021-12-07 07:11:21

I have this angular component where I like to add a custom input validator (see plunker).

我有这个角度组件,我想添加一个自定义输入验证器(参见plunker)。

I'm trying to access the ngModelController in the $onInit function. But it seams that the form is not populated at this time. Later on in the sendEmail() function it's no problem to access the the input model controller. How can I access the ngModelController and add a custom validator?

我正在尝试访问$ onInit函数中的ngModelController。但它接缝表示此时表格尚未填充。稍后在sendEmail()函数中访问输入模型控制器没问题。如何访问ngModelController并添加自定义验证器?

emailInput.js

(function(angular) {
  'use strict';

  function EmailInputController($log) {
    var ctrl = this;

    ctrl.$onInit = function() {
      // ctrl.myForm.myEmailInput is not populated 
      //$log.debug("Email view value is: "+(ctrl.myForm.myEmailInput.$viewValue));
    };

    ctrl.sendEmail = function() {
      $log.debug("EmailInputController.sendEmail");
      $log.debug("Email view value is: " + (ctrl.myForm.myEmailInput.$viewValue));
    };

  }

  angular.module('emailInputApp').component('emailInput', {
    templateUrl: 'emailInput.html',
    controller: EmailInputController,
  });
})(window.angular);

emailInput.html

<form name="$ctrl.myForm">
  <label>Email:</label>
  <input name="myEmailInput" type="email" ng-model="$ctrl.email" required maxlength="15">
  <button type="button" ng-click="$ctrl.sendEmail()">Send Email</button>
  <p>Your Email addres is {{$ctrl.email}}</p>
  <div ng-messages="$ctrl.myForm.myEmailInput.$error" role="alert">
    <div ng-message="required">Please enter an email address.</div>
    <div ng-message="email">This field must be a valid email address.</div>
    <div ng-message="maxlength">This field can be at most 15 characters long.</div>
  </div>
  <code>
    {{$ctrl.myForm.myEmailInput | json}}
  </code>
</form>

2 个解决方案

#1


2  

http://plnkr.co/edit/YQfGAsix1DON4ff3EWxz?p=preview

You can add watcher and remove it when not needed anymore.

您可以添加观察者并在不再需要时将其删除。

var removeWatch = $scope.$watch('$ctrl.myForm', function () {
        $log.debug("Email view value is: " + (ctrl.myForm.myEmailInput.$modelValue));

        removeWatch();
      });

#2


0  

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;

  return {
    require: 'ngModel',
    restrict: '',
    link: function(scope, elm, attrs, ctrl) {
      // only apply the validator if ngModel is present and Angular has added the email validator
      if (ctrl && ctrl.$validators.email) {

        // this will overwrite the default Angular email validator
        ctrl.$validators.email = function(modelValue) {
          return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
        };
      }
    }
  };
});

And simply add

只需添加

<input type='email' validate-email name='email' id='email' ng-model='email' required>  

#1


2  

http://plnkr.co/edit/YQfGAsix1DON4ff3EWxz?p=preview

You can add watcher and remove it when not needed anymore.

您可以添加观察者并在不再需要时将其删除。

var removeWatch = $scope.$watch('$ctrl.myForm', function () {
        $log.debug("Email view value is: " + (ctrl.myForm.myEmailInput.$modelValue));

        removeWatch();
      });

#2


0  

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;

  return {
    require: 'ngModel',
    restrict: '',
    link: function(scope, elm, attrs, ctrl) {
      // only apply the validator if ngModel is present and Angular has added the email validator
      if (ctrl && ctrl.$validators.email) {

        // this will overwrite the default Angular email validator
        ctrl.$validators.email = function(modelValue) {
          return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
        };
      }
    }
  };
});

And simply add

只需添加

<input type='email' validate-email name='email' id='email' ng-model='email' required>