salix/client/core/src/directives/validation.js

73 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-02-07 13:34:26 +00:00
import {module} from '../module';
import {validateAll} from '../lib/validator';
import {firstUpper} from '../lib/string';
2017-02-02 12:17:30 +00:00
2017-02-01 17:55:02 +00:00
directive.$inject = ['$interpolate', '$compile', '$window']
export function directive(interpolate, compile, $window) {
return {
restrict: 'A',
require: ['ngModel', '^^form'],
2017-02-02 12:17:30 +00:00
link: link
};
2017-02-01 17:55:02 +00:00
function link(scope, element, attrs, ctrl) {
2017-02-02 12:17:30 +00:00
let vnValidations = $window.validations;
2017-02-01 17:55:02 +00:00
if (!attrs.vnValidation || !vnValidations)
2017-02-02 12:17:30 +00:00
return;
2017-02-01 17:55:02 +00:00
let split = attrs.vnValidation.split('.');
2017-02-01 17:55:02 +00:00
if (split.length !== 2)
2017-02-02 12:17:30 +00:00
throw new Error(`vnValidation: Attribute must have this syntax: [entity].[field]`);
2017-02-01 17:55:02 +00:00
2017-02-02 12:17:30 +00:00
let entityName = firstUpper(split[0]);
let fieldName = split[1];
let entity = vnValidations[entityName];
2017-02-01 17:55:02 +00:00
if (!entity)
2017-02-02 12:17:30 +00:00
throw new Error(`vnValidation: Entity '${entityName}' doesn't exist`);
2017-02-02 12:17:30 +00:00
let validations = entity.validations[fieldName];
2017-02-01 17:55:02 +00:00
if (!validations || validations.length == 0)
2017-02-02 12:17:30 +00:00
return;
let errorMsg = angular.element('<span class="mdl-textfield__error"></span>');
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';
}
});
2017-02-01 17:55:02 +00:00
}
}
module.directive('vnValidation', directive);