UNPKG

@mantine/form

Version:

Mantine form management library

64 lines (63 loc) 2.08 kB
"use client"; import { getPath } from "../paths/get-path.mjs"; import { validateValues } from "./validate-values.mjs"; import { getRuleForPath } from "./get-rule-for-path.mjs"; //#region packages/@mantine/form/src/validate/validate-field-value.ts const defaultResolveError = (err) => err instanceof Error ? err.message : String(err); function fieldResultFromErrors(path, errors) { const pathInError = Object.keys(errors).find((errorKey) => path.split(".").every((pathPart, i) => pathPart === errorKey.split(".")[i])); return { hasError: !!pathInError, error: pathInError ? errors[pathInError] : null }; } function validateFieldValue(path, rules, values, resolveValidationError = defaultResolveError, signal = new AbortController().signal) { if (typeof path !== "string") return { hasError: false, error: null }; if (typeof rules === "function") { const results = validateValues(rules, values, resolveValidationError, signal); if (results instanceof Promise) return results.then((r) => fieldResultFromErrors(path, r.errors)); return fieldResultFromErrors(path, results.errors); } const rule = getRuleForPath(path, rules); if (rule) { const value = getPath(path, values); try { const result = rule(value, values, path, signal); if (result instanceof Promise) return result.then((error) => { if (error) return { hasError: true, error }; return { hasError: false, error: null }; }, (err) => ({ hasError: true, error: resolveValidationError(err) })); if (result) return { hasError: true, error: result }; return { hasError: false, error: null }; } catch (err) { return { hasError: true, error: resolveValidationError(err) }; } } const results = validateValues(rules, values, resolveValidationError, signal); if (results instanceof Promise) return results.then((r) => fieldResultFromErrors(path, r.errors)); return fieldResultFromErrors(path, results.errors); } //#endregion export { validateFieldValue }; //# sourceMappingURL=validate-field-value.mjs.map