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

时间:2016-05-22 06:13:05

标签: javascript angularjs

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

我正在尝试访问ngModelController函数中的$onInit。但它接缝表示此时表格尚未填充。稍后在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 个答案:

答案 0 :(得分:2)

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

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

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

        removeWatch();
      });

答案 1 :(得分: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);
        };
      }
    }
  };
});

只需添加

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