UNPKG

@yobta/validator

Version:
26 lines (25 loc) 892 B
import { fromEntries } from '../_internal/fromEntries/index.js'; import { rule } from '../rule/rule.js'; export const formMessage = 'It should be HTMLFormElement or a form Event'; export const form = (message = formMessage) => rule((value, ctx) => { if (value && value.target) { const { target } = value; const formNode = target.closest('form'); if (formNode) { ctx.form = formNode; } // NOTE: instanceof would not work for custom elements here: if (formNode && target !== formNode) { ctx.input = target; } } if (value instanceof HTMLFormElement) { ctx.form = value; } if (ctx.form) { // eslint-disable-next-line n/no-unsupported-features/node-builtins const output = new FormData(ctx.form); return fromEntries(output); } throw new Error(message); });