|
| 1 | +"use strict"; |
| 2 | +exports.__esModule = true; |
| 3 | +exports.validateRef = void 0; |
| 4 | +var vue_demi_1 = require("vue-demi"); |
| 5 | +var rulesList = { |
| 6 | + // Check if field is required (is not empty) |
| 7 | + required: function (value) { return !!value; }, |
| 8 | + // Check if value is not less than minimal length |
| 9 | + minLength: function (value, minLength) { return value.length >= minLength; }, |
| 10 | + // Check if value is not more than max length |
| 11 | + maxLength: function (value, maxLength) { return value.length <= maxLength; }, |
| 12 | + // Test value for email by regular expression |
| 13 | + email: function (value) { return /^\w+@[a-zA-Z_]+?\.?[a-z]+\.[a-zA-Z]{2,10}$/.test(value); }, |
| 14 | + // Check if value is a number |
| 15 | + numeric: function (value) { return !isNaN(value); }, |
| 16 | + // Check if value is a Date |
| 17 | + date: function (value) { |
| 18 | + var valueDate = new Date(value); |
| 19 | + var timeInMilliSecond = valueDate.valueOf(); |
| 20 | + var isInvalidDate = isNaN(timeInMilliSecond); |
| 21 | + return !isInvalidDate; |
| 22 | + } |
| 23 | +}; |
| 24 | +// Validate your variable and make it reactive |
| 25 | +function validateRef(model, rules) { |
| 26 | + // TODO: I can't type it. If you know how to do it please do it |
| 27 | + var localRules = {}; |
| 28 | + // Get input rules from global rules list and copy them to local rules |
| 29 | + rules.forEach(function (rule) { |
| 30 | + if (typeof rule === 'string') { |
| 31 | + localRules[rule] = rulesList[rule]; |
| 32 | + } |
| 33 | + else { |
| 34 | + localRules[rule.type] = { |
| 35 | + type: rulesList[rule.type], |
| 36 | + rule: rule.value |
| 37 | + }; |
| 38 | + } |
| 39 | + }); |
| 40 | + var value = (0, vue_demi_1.ref)(model); |
| 41 | + var modelRules = (0, vue_demi_1.ref)({}); |
| 42 | + var isValid = (0, vue_demi_1.ref)(false); |
| 43 | + (0, vue_demi_1.watch)(value, function () { |
| 44 | + // Loop through local rules array and run validation functions |
| 45 | + for (var rule in localRules) { |
| 46 | + if (typeof localRules[rule] === 'object') { |
| 47 | + modelRules.value[rule] = localRules[rule].type(value.value, localRules[rule].rule); |
| 48 | + } |
| 49 | + else { |
| 50 | + modelRules.value[rule] = localRules[rule](value.value); |
| 51 | + } |
| 52 | + } |
| 53 | + // Check if all rules are valid |
| 54 | + isValid.value = Object.values(modelRules.value).every(function (rule) { return rule; }); |
| 55 | + }, { immediate: true }); |
| 56 | + return (0, vue_demi_1.reactive)({ |
| 57 | + model: value, |
| 58 | + isValid: isValid, |
| 59 | + modelRules: modelRules |
| 60 | + }); |
| 61 | +} |
| 62 | +exports.validateRef = validateRef; |
0 commit comments