vue-yup-wrapper-reactive
Version:
Vue 3 composable plugin that integrates Yup validation with Vue reactive system for easy and type-safe form validation
135 lines (128 loc) • 4.82 kB
JavaScript
;
var vue = require('vue');
var Yup = require('yup');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var Yup__namespace = /*#__PURE__*/_interopNamespaceDefault(Yup);
const YUP = Yup__namespace;
const YUP_OBJECT = Yup__namespace.object;
// Example usage:
// const formConfig = {
// name: ['', YUP.string().required('Name is required'), 'Nama'],
// email: ['', YUP.string().email('Invalid email').required('Email is required')],
// age: [0, YUP.number().min(18, 'Must be at least 18 years old').required('Age is required')],
// password: ['', YUP.string().min(6, 'Password must be at least 6 characters').required('Password is required')],
// } as const
// Using the form:
// const { form, errors, validate, reset } = useYupForm(formConfig)
// Access form values
// console.log(form.name) // ''
// console.log(form.email) // ''
// console.log(form.age) // 0
// console.log(form.password) // ''
// Validate the form
// await validate()
// Check for errors
// console.log(errors.value) // Shows validation errors if any
// Reset form to initial values
// reset()
function useYupForm(config) {
const initialValues = Object.entries(config).reduce((acc, [key, [value]]) => {
acc[key] = value;
return acc;
}, {});
const schema = YUP_OBJECT().shape(Object.entries(config).reduce((acc, [key, [_, validator, label]]) => {
// Clone validator dan set custom label untuk error messages
const customValidator = validator.clone();
// Jika ada label, gunakan untuk error messages
if (label) {
// Override error messages untuk menggunakan label
customValidator.label(label);
}
acc[key] = customValidator;
return acc;
}, {}));
// Tambahkan fungsi untuk mendapatkan field labels/names
const getFieldLabel = (fieldKey) => {
const fieldConfig = config[fieldKey];
return fieldConfig[2] || String(fieldKey); // Gunakan rename jika ada, atau field key asli
};
// Tambahkan object untuk mapping field labels
const fieldLabels = Object.entries(config).reduce((acc, [key, [_, __, label]]) => {
acc[key] = label || key;
return acc;
}, {});
const form = vue.reactive({ ...initialValues });
const errors = vue.ref({});
async function validate() {
try {
await schema.validate(form, { abortEarly: false });
errors.value = {}; // clear all errors
return true;
}
catch (err) {
if (err instanceof Yup__namespace.ValidationError && Array.isArray(err.inner)) {
const newErrors = {};
err.inner.forEach((error) => {
if (error.path) {
// Dapatkan label field yang sudah di-rename
const fieldLabel = getFieldLabel(error.path);
// Ganti field name dalam error message dengan label yang sudah di-rename
const customMessage = error.message.replace(new RegExp(`\\b${error.path}\\b`, 'gi'), fieldLabel);
Object.assign(newErrors, { [error.path]: customMessage });
}
});
errors.value = newErrors;
}
else {
// Handle unexpected errors
console.error('Validation error:', err);
// state.errors = { _form: 'An unexpected error occurred' } as Partial<Record<keyof T, string>>;
}
return false;
}
}
const reset = () => {
Object.assign(form, initialValues);
errors.value = {};
};
return {
form,
errors,
reset,
validate,
getFieldLabel, // Export fungsi untuk mendapatkan label field
fieldLabels, // Export object mapping field labels
};
}
// Vue Yup Wrapper Reactive - Main Entry Point
// Export all public APIs
// Version info
const version = '1.0.0';
// Plugin info
const pluginInfo = {
name: 'vue-yup-wrapper-reactive',
version: '1.0.0',
description: 'Vue 3 composable plugin that integrates Yup validation with Vue reactive system',
author: 'Your Name'
};
exports.YUP = YUP;
exports.YUP_OBJECT = YUP_OBJECT;
exports.pluginInfo = pluginInfo;
exports.useYupForm = useYupForm;
exports.version = version;
//# sourceMappingURL=index.js.map