@chepchik/bind-form 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # bind-form
2
+
3
+ Что: один помощник `bindForm`, который вешает обработчик `submit` на форму,
4
+ валидирует поля по простой схеме (`required` / `pattern`) и вызывает
5
+ `onSubmit` с собранными значениями, если всё валидно.
6
+
7
+ Зачем: чтобы не дублировать в каждой форме одинаковый код —
8
+ `preventDefault`, сбор `FormData`, проверку обязательных полей и regex,
9
+ показ/скрытие текста ошибки. Отправка по Enter работает "из коробки",
10
+ т.к. используется стандартное поведение `<form>`.
11
+
12
+ ## Установка
13
+
14
+ ```sh
15
+ npm install @chepchik/bind-form
16
+ ```
17
+
18
+ ## Использование
19
+
20
+ ```ts
21
+ import { bindForm } from "@chepchik/bind-form";
22
+
23
+ const form = document.querySelector("form")!;
24
+ const errorElement = document.querySelector("#error")!;
25
+
26
+ const unsubscribe = bindForm(form, {
27
+ schema: {
28
+ email: { required: "Введите email", pattern: { value: /.+@.+/, message: "Неверный email" } },
29
+ password: { required: "Введите пароль" },
30
+ },
31
+ errorElement,
32
+ resetOnSuccess: true,
33
+ onSubmit: async (values, form) => {
34
+ await api.login(values.email, values.password);
35
+ },
36
+ });
37
+
38
+ // позже, при размонтировании:
39
+ unsubscribe();
40
+ ```
41
+
42
+ ## API
43
+
44
+ ### `bindForm<TField>(form, options): () => void`
45
+
46
+ - `form: HTMLFormElement` — форма, на которую вешается обработчик `submit`.
47
+ - `options.schema: Record<TField, FieldRule>` — схема валидации, ключи
48
+ должны совпадать с атрибутами `name` полей формы.
49
+ - `required?: string` — текст ошибки, если поле пустое после `trim()`.
50
+ - `pattern?: { value: RegExp; message: string }` — проверяется только
51
+ если поле непустое.
52
+ - `options.errorElement?: HTMLElement` — элемент для показа текста ошибки
53
+ (должен поддерживать атрибут `hidden`).
54
+ - `options.onSubmit(values, form)` — вызывается после успешной валидации.
55
+ - `options.resetOnSuccess?: boolean` — сбросить форму после успешного `onSubmit`.
56
+
57
+ Возвращает функцию отписки от события `submit`.
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Subscribes to a form's submit event: prevents the page reload, validates fields
3
+ * against the schema (required/pattern) and calls onSubmit with the collected values.
4
+ * Submitting via Enter works out of the box (default <form> behavior).
5
+ * Returns an unsubscribe function.
6
+ */
7
+ export declare function bindForm<TField extends string>(form: HTMLFormElement, options: BindFormOptions<TField>): () => void;
8
+
9
+ export declare interface BindFormOptions<TField extends string> {
10
+ /** Validation schema: keys must match the `name` attributes of the form fields. */
11
+ schema: Record<TField, FieldRule>;
12
+ /** Element used to display the validation error message (must support `hidden`). */
13
+ errorElement?: HTMLElement;
14
+ /** Called with the validated values after a successful submit. */
15
+ onSubmit: (values: FormValues<TField>, form: HTMLFormElement) => void | Promise<void>;
16
+ /** Reset the form after a successful onSubmit. */
17
+ resetOnSuccess?: boolean;
18
+ }
19
+
20
+ /** Validation rule for a single form field. */
21
+ export declare interface FieldRule {
22
+ /** Error message shown if the field is empty after trim(). */
23
+ required?: string;
24
+ /** Regex and error message checked only when the field is non-empty. */
25
+ pattern?: {
26
+ value: RegExp;
27
+ message: string;
28
+ };
29
+ }
30
+
31
+ /** Form values: field name -> string value taken from FormData. */
32
+ export declare type FormValues<TField extends string> = Record<TField, string>;
33
+
34
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ function m(e, t) {
2
+ const u = (c) => {
3
+ c.preventDefault();
4
+ const d = new FormData(e), a = {};
5
+ let r;
6
+ for (const s of Object.keys(t.schema)) {
7
+ const i = String(d.get(s) ?? "").trim();
8
+ a[s] = i;
9
+ const n = t.schema[s];
10
+ !r && n.required && !i ? r = n.required : !r && i && n.pattern && !n.pattern.value.test(i) && (r = n.pattern.message);
11
+ }
12
+ if (r) {
13
+ f(t.errorElement, r);
14
+ return;
15
+ }
16
+ o(t.errorElement), Promise.resolve(t.onSubmit(a, e)).then(() => {
17
+ t.resetOnSuccess && e.reset();
18
+ });
19
+ };
20
+ return e.addEventListener("submit", u), () => e.removeEventListener("submit", u);
21
+ }
22
+ function f(e, t) {
23
+ e && (e.textContent = t, e.removeAttribute("hidden"));
24
+ }
25
+ function o(e) {
26
+ e && e.setAttribute("hidden", "");
27
+ }
28
+ export {
29
+ m as bindForm
30
+ };
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@chepchik/bind-form",
3
+ "version": "0.1.0",
4
+ "description": "Tiny dependency-free form binding helper: submit handling, validation schema and error display.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": ["dist"],
16
+ "sideEffects": false,
17
+ "scripts": {
18
+ "build": "vite build",
19
+ "dev": "vite build --watch"
20
+ },
21
+ "keywords": ["form", "validation", "spa"],
22
+ "license": "MIT",
23
+ "devDependencies": {
24
+ "typescript": "^5.6.0",
25
+ "vite": "^6.0.0",
26
+ "vite-plugin-dts": "^4.3.0"
27
+ }
28
+ }