Q: How to add custom validation to an angular component? I have this angular component where I like to add a custom input validator (see 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?
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>


A: 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();
      });


A: 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>  

