@jay-js/system
Version:
A powerful and flexible TypeScript library for UI, state management, lazy loading, routing and managing draggable elements in modern web applications.
51 lines • 2.41 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
/**
* A resolver function for validating form values using a Yup schema.
*
* @template T - The type of the form values.
* @param {ObjectSchema<any>} schema - The Yup schema to validate against.
* @returns {TResolver<T>} - A resolver function that validates the form values and returns validation errors, if any.
*
* The resolver function takes the form values and an optional field name as input.
* If a field name is provided, it validates only that field. Otherwise, it validates the entire form.
*
* The function returns an object containing an array of errors. Each error includes:
* - `path`: The path of the field with the error.
* - `message`: The error message.
*
* If no errors are found, the `errors` array will be empty.
*/
export function yupResolver(schema) {
return (values, fieldName) => __awaiter(this, void 0, void 0, function* () {
try {
if (fieldName) {
yield schema.validateAt(fieldName, values, { abortEarly: false });
}
else {
yield schema.validate(values, { abortEarly: false });
}
return { errors: [] };
}
catch (error) {
if (error === null || error === void 0 ? void 0 : error.inner) {
const formattedErrors = error.inner.length > 0 ? error.inner : [error];
return {
errors: formattedErrors.map((err) => ({
path: err.path || "unknown",
message: err.message,
})),
};
}
return { errors: [{ path: "unknown", message: "Unknown error" }] };
}
});
}
//# sourceMappingURL=yup-resolver.js.map