salix-front/src/composables/useValidator.js

82 lines
2.6 KiB
JavaScript
Raw Normal View History

2022-10-18 12:58:41 +00:00
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import validator from 'validator';
const models = ref(null);
export function useValidator() {
if (!models.value) fetch();
function fetch() {
axios.get('Schemas/ModelInfo')
.then(response => models.value = response.data)
}
function validate(propertyRule) {
const modelInfo = models.value;
if (!modelInfo || !propertyRule) return;
const rule = propertyRule.split('.');
const model = rule[0];
const property = rule[1];
const modelName = model.charAt(0).toUpperCase() + model.slice(1);
if (!modelInfo[modelName]) return;
const modelValidations = modelInfo[modelName].validations;
if (!modelValidations[property]) return;
const rules = modelValidations[property].map((validation) => {
return validations(validation)[validation.validation];
});
return rules;
}
const { t } = useI18n();
const validations = function (validation) {
2022-10-20 11:42:49 +00:00
2022-10-18 12:58:41 +00:00
return {
2022-10-20 11:42:49 +00:00
presence: (value) => {
let message = `Value can't be empty`;
if (validation.message)
message = t(validation.message) || validation.message
return !validator.isEmpty(value ? String(value) : '') || message
},
2022-10-18 12:58:41 +00:00
length: (value) => {
const options = {
min: validation.min || validation.is,
max: validation.max || validation.is
};
value = String(value);
if (!value) value = '';
let message = `Value should have at most ${options.max} characters`;
if (validation.is)
message = `Value should be ${validation.is} characters long`;
if (validation.min)
message = `Value should have at least ${validation.min} characters`;
if (validation.min && validation.max)
message = `Value should have a length between ${validation.min} and ${validation.max}`;
return validator.isLength(value, options) || message;
},
numericality: (value) => {
if (validation.int)
return validator.isInt(value) || 'Value should be integer'
return validator.isNumeric(value) || 'Value should be a number'
},
custom: (value) => validation.bindedFunction(value) || 'Invalid value'
};
};
return {
validate
};
}