import {module} from './module'; import {validateAll} from './validator.js'; 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 input = ctrl[0], form = ctrl[1]; let template = ''; let messageNode = interpolate(template)({form: form.$name, input: input.$name}); messageNode = angular.element(messageNode); input.$validators['remote'] = function(value) { return isValid(value, validations, messageNode, element); } element.after(compile(messageNode)(scope)); } function firstUpper(str) { return str.charAt(0).toUpperCase() + str.substr(1); } function isValid(value, validations, messageNode, element) { let parent = element.parent(); try { validateAll(value, validations) } catch(e) { messageNode.text(e.message); parent.attr('title', e.message); parent.addClass('invalid'); return false; } parent.removeClass('invalid'); return true; } } module.directive('vnValidation', directive);