salix/front/core/directives/validation.js

81 lines
2.4 KiB
JavaScript
Raw Normal View History

2018-02-10 15:18:01 +00:00
import ngModule from '../module';
2017-02-07 13:34:26 +00:00
import {validateAll} from '../lib/validator';
import {firstUpper} from '../lib/string';
2017-02-02 12:17:30 +00:00
directive.$inject = ['$interpolate', '$compile', '$translate', '$window'];
export function directive(interpolate, compile, $translate, $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];
if (!validations || validations.length == 0)
2017-02-02 12:17:30 +00:00
return;
let ngModel = ctrl[0];
let form = ctrl[1];
let errorSpan = angular.element('<span class="mdl-textfield__error"></span>');
let errorMsg;
let errorShown = false;
ngModel.$options.$$options.allowInvalid = true;
ngModel.$validators.entity = value => {
try {
validateAll($translate, value, validations);
2017-03-07 12:01:24 +00:00
return true;
} catch (e) {
errorMsg = e.message;
if (errorShown) changeError();
return false;
}
};
2018-01-02 07:05:50 +00:00
scope.$watch(() => {
return (form.$submitted || ngModel.$dirty) && ngModel.$invalid;
2018-01-02 07:05:50 +00:00
}, value => {
let parent = element.parent();
if (value) {
changeError();
parent.addClass('invalid');
element.after(errorSpan);
} else if (errorShown) {
parent.removeClass('invalid');
parent.removeAttr('title');
errorSpan.remove();
errorSpan.empty();
}
errorShown = value;
});
function changeError() {
let parent = element.parent();
errorSpan.text(errorMsg);
parent.attr('title', errorMsg);
}
2017-02-01 17:55:02 +00:00
}
}
2018-02-10 15:18:01 +00:00
ngModule.directive('vnValidation', directive);
2017-02-01 17:55:02 +00:00