salix/client/core/src/validation.js

83 lines
3.3 KiB
JavaScript
Raw Normal View History

import {module} from './module';
directive.$inject = ['$interpolate', '$compile', 'validationRules', 'validatorjs']
export function directive(interpolate, compile, validationRules, validatorjs) {
return {
restrict: 'A',
require: ['ngModel', '^^form'],
link: function (scope, element, attrs, ctrl) {
var validator = scope.$eval(attrs.validation, validationRules),
input = ctrl[0],
form = ctrl[1],
messages = [],
customValidator = {},
parentMessage;
scope.$on('destroy', function () {
customValidator = null;
});
function isFunction(key) {
return key && typeof validator[key] === 'function';
}
function setError(key,message) {
var validator;
(validator=customValidator[key]) && validator.text(message);
}
function validate(key) {
return function (value) {
var params = [value].concat((validator[key].args || [])),
_validator = validator[key],
isValid = false;
if (isFunction(key)) {
try {
_validator(value);
return true;
}
catch (error) {
setError(key,error.message)
return false;
}
} else {
isValid = validatorjs[key].apply(validatorjs, params);
if (!isValid) {
setError(key,_validator.msg)
}
return isValid;
}
}
}
function createMessage(form, input, key) {
2017-02-01 09:05:15 +00:00
var template = '<div ng-show="{{form}}.$dirty && {{form}}.{{input}}.$error.{{key}}"></div>';
var span = interpolate(template)({ form: form, input: input, key: key });
var element = angular.element(span);
return element;
}
function createMessages(form, input) {
2017-02-01 09:05:15 +00:00
var template = '<div text-light tooltip-message ng-show="{{form}}.$dirty && {{form}}.{{input}}.$invalid"></div>';
return interpolate(template)({ form: form, input: input });
}
if (validator) {
Object.keys(validator).forEach(function (key) {
var element = createMessage(form.$name, input.$name, key);
input.$validators[key] = validate(key);
customValidator[key] = element;
messages.push(element);
});
if (messages.length > 0) {
parentMessage = angular.element(createMessages(form.$name, input.$name));
messages.forEach(function (item) {
parentMessage.append(item);
});
messages = null;
element.after(compile(parentMessage)(scope));
}
}
}
}
}
module.directive('vnValidation', directive);