import {module} from '../module'; import {validateAll} from '../lib/validator'; import {firstUpper} from '../lib/string'; directive.$inject = ['$interpolate', '$compile', '$window'] export function directive(interpolate, compile, $window) { return { restrict: 'A', require: ['ngModel', '^^form'], link: link }; function link(scope, element, attrs, ctrl) { let vnValidations = $window.validations; if (!attrs.vnValidation || !vnValidations) return; let split = attrs.vnValidation.split('.'); if (split.length !== 2) throw new Error(`vnValidation: Attribute must have this syntax: [entity].[field]`); let entityName = firstUpper(split[0]); let fieldName = split[1]; let entity = vnValidations[entityName]; if (!entity) throw new Error(`vnValidation: Entity '${entityName}' doesn't exist`); let validations = entity.validations[fieldName]; if (!validations || validations.length == 0) return; let errorMsg = angular.element(''); element.after(errorMsg); let input = ctrl[0]; let form = ctrl[1]; input.$validators.entity = function(value) { let parent = element.parent(); try { validateAll(value, validations); } catch (e) { errorMsg.text(e.message); parent.attr('title', e.message); return false; } return true; }; scope.$watch(function() { return (form.$submitted || input.$dirty) && input.$invalid; }, function(value) { let parent = element.parent(); if (value) { parent.addClass('invalid'); errorMsg[0].style.display = 'block'; } else { parent.removeClass('invalid'); errorMsg[0].style.display = 'none'; } }); } } module.directive('vnValidation', directive);