AngularJS Example:

by soumya gangamwar

HTML

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<div ng-app="myApp">
  {{ myForm.$invalid }}------------
  <form name="myForm" novalidate>
    <button disabled="{{ myForm.$invalid }}">Save</button>
    <label>
       Last name:
       <input type="text" name="lastName" ng-model="user.last"
       ng-minlength="5" ng-maxlength="10" my-directive config="'lastName'">
    </label>
    <div role="alert">
      <span class="error" ng-show="myForm.lastName.$error.minlength">
        Too short!</span>
      <span class="error" ng-show="myForm.lastName.$error.maxlength">
        Too long!</span>
    </div>
    <span id="test"></span> First name:
    <input type="text" name="firstName" ng-model="user.first" ng-minlength="5" my-directive config="'firstName'">
    </label>
    <div role="alert">
      <span class="error" ng-show="myForm.firstName.$error.minlength">
        Too short!</span>

    </div>
    <span id="test"></span>

  </form>
</div>

JavaScript

var app = angular.module('myApp', []);
app.directive('myDirective', function($compile) {
  return {
    require: 'ngModel',
    scope: {
      config: '='
    },

    link: function(scope, element, attr, mCtrl) {
      console.log(scope, 'ssss', scope.config)

      var msg = document.createElement("p");
      var node = document.createTextNode(scope.config + "validation from directive");
      msg.appendChild(node);

      element.bind('blur', function() {

        console.log('test', mCtrl.$error, Object.entries(mCtrl.$error));


        var selectedfield = mCtrl.$error;

        var fields = Object.entries(mCtrl.$error);

        fields.map((field) => {
          console.log(selectedfield, 'field[0]', field[0])
          if (selectedfield[field[0]]) {
            console.log('TTTT')
          } else {
            console.log('EEEEE')
            angular.element(document.getElementById('test')).append($compile(msg)(scope));
          }
        })


        //  mCtrl.append(msg)
      })

      element.bind('focus', function() {
        console.log('focus');
        // angular.element(document.getElementById('test')).remove()(scope));
      })
      /** function myValidation(value) {
           if (value.indexOf("e") > -1) {
               mCtrl.$setValidity('charE', true);
           } else {
               mCtrl.$setValidity('charE', false);
           }
           return value;
       }
       mCtrl.$parsers.push(myValidation);**/
    }
  };
});