@docvhcmc/react-form-schema
Version:
A flexible React form schema manager with pluggable validation adapters (Zod, Yup, etc.)
100 lines (96 loc) • 3.02 kB
JavaScript
// src/constants/errorCodes.ts
var ValidationCode = /* @__PURE__ */ ((ValidationCode2) => {
ValidationCode2["FIELD_UNKNOWN"] = "FIELD_UNKNOWN";
ValidationCode2["UNEXPECTED"] = "UNEXPECTED";
return ValidationCode2;
})(ValidationCode || {});
// src/core/FormErrorManager.ts
var FormErrorManager = class {
_errors = [];
constructor(initialErrors = []) {
this._errors = initialErrors;
}
/**
* Sets all errors at once, replacing any existing errors.
* @param errors An array of FieldError objects.
*/
setErrors(errors) {
this._errors = errors;
}
/**
* Adds a single error to the current list of errors.
* @param error The FieldError object to add.
*/
addError(error) {
this._errors.push(error);
}
/**
* Checks if any error exists for a specific field path, or if any error exists in general.
* @param path Optional. The dot-notation path of the field (e.g., 'name', 'address.street').
* @returns `true` if an error exists for the specified path or if any error exists, `false` otherwise.
*/
hasError(path) {
if (!path) {
return this._errors.length > 0;
}
return this._errors.some((error) => error.path === path);
}
/**
* Retrieves the first error message for a specific field.
* @param path The dot-notation path of the field.
* @returns The error message string, or `undefined` if the field has no error.
*/
getFirstFieldError(path) {
return this._errors.find((error) => error.path === path)?.message;
}
/**
* Retrieves all error objects for a specific field.
* @param path The dot-notation path of the field.
* @returns An array of `FieldError` objects for the specified field.
*/
getErrorsForField(path) {
return this._errors.filter((error) => error.path === path);
}
/**
* Retrieves all current error objects.
* @returns An array of all `FieldError` objects.
*/
getAllErrors() {
return [...this._errors];
}
/**
* Clears all existing errors.
*/
clearErrors() {
this._errors = [];
}
};
// src/errors/ValidationError.ts
var ValidationError = class _ValidationError extends Error {
fields;
/**
* Optionally store the original error (e.g., ZodError) for debugging
*/
originalError;
/**
* Creates an instance of ValidationError.
* @param fields An array of FieldError objects.
* @param originalError The original error object from the validator (optional).
* @param message A custom error message (optional). If not provided, a default message is generated.
*/
constructor(fields, originalError, message) {
const defaultMessage = fields.map((f) => `${f.path}: ${f.message}`).join(", ") || "Validation failed.";
super(message || defaultMessage);
this.name = "ValidationError";
this.fields = fields;
this.originalError = originalError;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, _ValidationError);
}
}
};
export {
ValidationCode,
FormErrorManager,
ValidationError
};