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

82 lines
2.4 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-03-07 12:01:24 +00:00
directive.$inject = ['$interpolate', '$compile', '$window'];
2017-02-01 17:55:02 +00:00
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 input = ctrl[0];
let form = ctrl[1];
let errorSpan = angular.element('<span class="mdl-textfield__error"></span>');
let errorMsg;
let errorShown = false;
2017-09-13 07:45:42 +00:00
input.$options.$$options.allowInvalid = true;
input.$validators.entity = function(value) {
try {
validateAll(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 || input.$dirty) && input.$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
}
}
module.directive('vnValidation', directive);