salix/client/core/src/validation.js

70 lines
2.1 KiB
JavaScript
Raw Normal View History

import {module} from './module';
2017-02-02 12:17:30 +00:00
import {validateAll} from './validator.js';
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
2017-02-02 12:17:30 +00:00
function link (scope, element, attrs, ctrl) {
let vnValidations = $window.validations;
2017-02-01 17:55:02 +00:00
2017-02-02 12:17:30 +00:00
if(!attrs['vnValidation'] || ! vnValidations)
return;
2017-02-01 17:55:02 +00:00
2017-02-02 12:17:30 +00:00
let split = attrs['vnValidation'].split('.');
2017-02-01 17:55:02 +00:00
2017-02-02 12:17:30 +00:00
if(split.length != 2)
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
2017-02-02 12:17:30 +00:00
if(!entity)
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
2017-02-02 12:17:30 +00:00
if(!validations || validations.length == 0)
return;
2017-02-02 12:17:30 +00:00
let input = ctrl[0],
form = ctrl[1];
2017-02-01 17:55:02 +00:00
2017-02-02 12:17:30 +00:00
let template = '<span class="mdl-textfield__error" ng-show="{{form}}.$dirty && {{form}}.{{input}}.$invalid"></span>';
let messageNode = interpolate(template)({form: form.$name, input: input.$name});
messageNode = angular.element(messageNode);
2017-02-01 17:55:02 +00:00
2017-02-02 12:17:30 +00:00
input.$validators['remote'] = function(value) {
return isValid(value, validations, messageNode, element);
2017-02-01 17:55:02 +00:00
}
2017-02-02 12:17:30 +00:00
element.after(compile(messageNode)(scope));
}
2017-02-01 17:55:02 +00:00
function firstUpper(str) {
return str.charAt(0).toUpperCase() + str.substr(1);
}
2017-02-02 12:17:30 +00:00
function isValid(value, validations, messageNode, element) {
let parent = element.parent();
2017-02-01 17:55:02 +00:00
2017-02-02 09:52:09 +00:00
try {
2017-02-02 12:17:30 +00:00
validateAll(value, validations)
2017-02-02 09:52:09 +00:00
}
catch(e) {
2017-02-02 12:17:30 +00:00
messageNode.text(e.message);
parent.attr('title', e.message);
parent.addClass('invalid');
2017-02-02 09:52:09 +00:00
return false;
}
2017-02-01 17:55:02 +00:00
2017-02-02 12:17:30 +00:00
parent.removeClass('invalid');
2017-02-02 09:52:09 +00:00
return true;
2017-02-01 17:55:02 +00:00
}
}
module.directive('vnValidation', directive);