@chepchik/bind-form 0.1.0 → 0.1.2

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 CHANGED
@@ -1,11 +1,16 @@
1
1
  # bind-form
2
2
 
3
3
  Что: один помощник `bindForm`, который вешает обработчик `submit` на форму,
4
- валидирует поля по простой схеме (`required` / `pattern`) и вызывает
5
- `onSubmit` с собранными значениями, если всё валидно.
4
+ валидирует поля по схеме (`required` / `pattern` / `minLength` / `maxLength` /
5
+ `min` / `max` / `validate`, опционально + `resolver`) и вызывает `onSubmit`
6
+ с собранными значениями, если всё валидно. Опционально умеет валидировать
7
+ поля "на лету" (`validateOn: "blur" | "input"`), показывать ошибку для
8
+ каждого поля отдельно, отслеживать `dirty`/`touched`/`isSubmitting`
9
+ (`onStateChange`, `getState`), реагировать на изменения отдельного поля
10
+ (`watch`) и блокировать кнопку отправки на время `onSubmit`.
6
11
 
7
12
  Зачем: чтобы не дублировать в каждой форме одинаковый код —
8
- `preventDefault`, сбор `FormData`, проверку обязательных полей и regex,
13
+ `preventDefault`, сбор `FormData`, проверку полей и regex,
9
14
  показ/скрытие текста ошибки. Отправка по Enter работает "из коробки",
10
15
  т.к. используется стандартное поведение `<form>`.
11
16
 
@@ -23,12 +28,16 @@ import { bindForm } from "@chepchik/bind-form";
23
28
  const form = document.querySelector("form")!;
24
29
  const errorElement = document.querySelector("#error")!;
25
30
 
26
- const unsubscribe = bindForm(form, {
31
+ const formHandle = bindForm(form, {
27
32
  schema: {
28
33
  email: { required: "Введите email", pattern: { value: /.+@.+/, message: "Неверный email" } },
29
- password: { required: "Введите пароль" },
34
+ password: {
35
+ required: "Введите пароль",
36
+ minLength: { value: 6, message: "Минимум 6 символов" },
37
+ },
30
38
  },
31
39
  errorElement,
40
+ validateOn: "blur",
32
41
  resetOnSuccess: true,
33
42
  onSubmit: async (values, form) => {
34
43
  await api.login(values.email, values.password);
@@ -36,12 +45,79 @@ const unsubscribe = bindForm(form, {
36
45
  });
37
46
 
38
47
  // позже, при размонтировании:
39
- unsubscribe();
48
+ formHandle();
49
+ ```
50
+
51
+ Для показа ошибки конкретного поля при `validateOn` добавьте рядом с полем
52
+ элемент `[data-error-for="<name>"]` (`<span data-error-for="email" hidden></span>`).
53
+
54
+ ## Пример: сложная форма
55
+
56
+ Более развёрнутый пример, использующий все возможности: `resolver` для
57
+ асинхронной проверки, `onStateChange` для индикации состояния, `watch` для
58
+ живого фидбека по отдельному полю и блокировку кнопки на время отправки.
59
+ Рабочая версия — страница `/form-demo` в `OOP_taskList`
60
+ (`app/pages/form-demo/index.page.ts`).
61
+
62
+ ```ts
63
+ import { bindForm, type FormErrors } from "@chepchik/bind-form";
64
+
65
+ type Field = "username" | "password" | "bio";
66
+
67
+ const submitButton = form.querySelector<HTMLButtonElement>('[type="submit"]')!;
68
+ const bioCount = document.querySelector("#bio-count")!;
69
+ const passwordStrength = document.querySelector("#password-strength")!;
70
+
71
+ const handle = bindForm<Field>(form, {
72
+ schema: {
73
+ username: {
74
+ required: "Введите имя пользователя",
75
+ minLength: { value: 3, message: "Минимум 3 символа" },
76
+ },
77
+ password: {
78
+ required: "Введите пароль",
79
+ minLength: { value: 6, message: "Минимум 6 символов" },
80
+ validate: (value) => (/\d/.test(value) ? undefined : "Пароль должен содержать цифру"),
81
+ },
82
+ bio: {
83
+ maxLength: { value: 200, message: "Максимум 200 символов" },
84
+ },
85
+ },
86
+ validateOn: "input",
87
+ // Асинхронная проверка, выполняется на submit после правил schema.
88
+ resolver: async (values): Promise<FormErrors<Field>> => {
89
+ const taken = await api.isUsernameTaken(values.username);
90
+ return taken ? { username: "Это имя уже занято" } : {};
91
+ },
92
+ // Отслеживание состояния формы.
93
+ onStateChange: (state) => {
94
+ submitButton.textContent = state.isSubmitting ? "Отправка..." : "Зарегистрироваться";
95
+ },
96
+ onSubmit: async (values) => {
97
+ await api.register(values);
98
+ },
99
+ resetOnSuccess: true,
100
+ });
101
+
102
+ // Живой фидбек по отдельным полям.
103
+ handle.watch("bio", (value) => {
104
+ bioCount.textContent = `${value.length}/200`;
105
+ });
106
+ handle.watch("password", (value) => {
107
+ passwordStrength.textContent = value.length >= 10 ? "сильный" : "слабый";
108
+ });
109
+
110
+ // Программное управление формой.
111
+ fillExampleButton.addEventListener("click", () => {
112
+ handle.setValue("username", "ivan_petrov");
113
+ handle.setValue("password", "secret123");
114
+ });
115
+ resetButton.addEventListener("click", () => handle.reset());
40
116
  ```
41
117
 
42
118
  ## API
43
119
 
44
- ### `bindForm<TField>(form, options): () => void`
120
+ ### `bindForm<TField>(form, options): BindFormHandle<TField>`
45
121
 
46
122
  - `form: HTMLFormElement` — форма, на которую вешается обработчик `submit`.
47
123
  - `options.schema: Record<TField, FieldRule>` — схема валидации, ключи
@@ -49,9 +125,49 @@ unsubscribe();
49
125
  - `required?: string` — текст ошибки, если поле пустое после `trim()`.
50
126
  - `pattern?: { value: RegExp; message: string }` — проверяется только
51
127
  если поле непустое.
52
- - `options.errorElement?: HTMLElement` — элемент для показа текста ошибки
128
+ - `minLength?: { value: number; message: string }` / `maxLength?: { ... }` —
129
+ длина строки после `trim()`.
130
+ - `min?: { value: number; message: string }` / `max?: { ... }` — проверяются,
131
+ только если значение поля парсится как число.
132
+ - `validate?: (value: string) => string | undefined` — кастомная проверка,
133
+ выполняется последней.
134
+ - `options.errorElement?: HTMLElement` — элемент для показа общей ошибки формы
53
135
  (должен поддерживать атрибут `hidden`).
136
+ - `options.validateOn?: "blur" | "input"` — дополнительно валидировать поле
137
+ при потере фокуса/вводе и показывать ошибку в `[data-error-for="<field>"]`.
138
+ - `options.resolver?: (values) => FormErrors<TField> | Promise<FormErrors<TField>>` —
139
+ доп. асинхронная/внешняя валидация (например, обёртка над zod/yup-схемой),
140
+ выполняется на submit после проверок из `schema`. Для поля, у которого
141
+ `schema` уже нашла ошибку, результат resolver'а игнорируется.
142
+ - `options.onStateChange?: (state: FormState<TField>) => void` — вызывается
143
+ при изменении значений/ошибок/`touched`/`dirty`/`isSubmitting`.
144
+ - `options.disableSubmitWhilePending?: boolean` — отключать `[type="submit"]`
145
+ на время выполнения `onSubmit`. По умолчанию `true`.
54
146
  - `options.onSubmit(values, form)` — вызывается после успешной валидации.
55
147
  - `options.resetOnSuccess?: boolean` — сбросить форму после успешного `onSubmit`.
56
148
 
57
- Возвращает функцию отписки от события `submit`.
149
+ ### `FormState<TField>`
150
+
151
+ - `values: FormValues<TField>` — текущие значения.
152
+ - `errors: FormErrors<TField>` — текущие ошибки по полям.
153
+ - `touched: Record<TField, boolean>` — было ли поле в фокусе/изменено
154
+ (`blur`/`input`) с момента привязки или последнего `reset()`.
155
+ - `dirty: Record<TField, boolean>` — отличается ли значение поля от значения
156
+ на момент привязки/последнего `reset()`.
157
+ - `isDirty: boolean` — true, если хотя бы одно поле `dirty`.
158
+ - `isSubmitting: boolean` — true во время выполнения `onSubmit`.
159
+
160
+ ### `BindFormHandle<TField>`
161
+
162
+ Сама функция — отписка от обработчиков (вызовите `formHandle()` при размонтировании).
163
+ Дополнительно доступны методы:
164
+
165
+ - `getValues(): FormValues<TField>` — текущие (обрезанные) значения полей.
166
+ - `setValue(field, value: string)` — записать значение в поле формы.
167
+ - `setError(field, message?: string)` — показать/скрыть ошибку поля
168
+ (`[data-error-for="<field>"]`).
169
+ - `reset()` — сбросить форму, очистить все отображённые ошибки и пересчитать
170
+ базовые значения для `dirty`/`touched`.
171
+ - `getState(): FormState<TField>` — снимок текущего состояния формы.
172
+ - `watch(field, callback)` — вызывать `callback(value, values)` при каждом
173
+ изменении значения `field`. Возвращает функцию отписки.
package/dist/index.d.ts CHANGED
@@ -1,34 +1,110 @@
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 { }
1
+ /** Validation rule for a single form field. */
2
+ export interface FieldRule {
3
+ /** Error message shown if the field is empty after trim(). */
4
+ required?: string;
5
+ /** Regex and error message checked only when the field is non-empty. */
6
+ pattern?: {
7
+ value: RegExp;
8
+ message: string;
9
+ };
10
+ /** Minimum string length (after trim()), checked only when the field is non-empty. */
11
+ minLength?: {
12
+ value: number;
13
+ message: string;
14
+ };
15
+ /** Maximum string length (after trim()). */
16
+ maxLength?: {
17
+ value: number;
18
+ message: string;
19
+ };
20
+ /** Minimum numeric value, checked only when the field parses as a number. */
21
+ min?: {
22
+ value: number;
23
+ message: string;
24
+ };
25
+ /** Maximum numeric value, checked only when the field parses as a number. */
26
+ max?: {
27
+ value: number;
28
+ message: string;
29
+ };
30
+ /** Custom validator, run last. Return an error message, or undefined/empty string if valid. */
31
+ validate?: (value: string) => string | undefined;
32
+ }
33
+ /** Form values: field name -> string value taken from FormData. */
34
+ export type FormValues<TField extends string> = Record<TField, string>;
35
+ /** Validation errors keyed by field name. */
36
+ export type FormErrors<TField extends string> = Partial<Record<TField, string>>;
37
+ /** When to run per-field validation in addition to submit. */
38
+ export type ValidateTrigger = "blur" | "input";
39
+ /** Snapshot of the form's current state, passed to `onStateChange`. */
40
+ export interface FormState<TField extends string> {
41
+ values: FormValues<TField>;
42
+ errors: FormErrors<TField>;
43
+ /** Whether a field has been interacted with (blur/input) since bind or last reset. */
44
+ touched: Record<TField, boolean>;
45
+ /** Whether a field's value differs from its value at bind time (or last reset). */
46
+ dirty: Record<TField, boolean>;
47
+ /** True if any field is dirty. */
48
+ isDirty: boolean;
49
+ /** True while `onSubmit` is pending. */
50
+ isSubmitting: boolean;
51
+ }
52
+ export interface BindFormOptions<TField extends string> {
53
+ /** Validation schema: keys must match the `name` attributes of the form fields. */
54
+ schema: Record<TField, FieldRule>;
55
+ /** Element used to display the form-level error message (must support `hidden`). */
56
+ errorElement?: HTMLElement;
57
+ /**
58
+ * Run validation for a field as the user interacts with it, in addition to on submit.
59
+ * Per-field errors are shown in elements matching `[data-error-for="<field>"]` inside the form.
60
+ */
61
+ validateOn?: ValidateTrigger;
62
+ /**
63
+ * Additional async/external validation (e.g. a zod/yup schema adapter), run on submit
64
+ * after the `schema` rules. Only consulted for fields that passed `schema` validation.
65
+ */
66
+ resolver?: (values: FormValues<TField>) => FormErrors<TField> | Promise<FormErrors<TField>>;
67
+ /** Called whenever the form's values/errors/touched/dirty/submitting state changes. */
68
+ onStateChange?: (state: FormState<TField>) => void;
69
+ /**
70
+ * Disable `[type="submit"]` elements inside the form while `onSubmit` is pending.
71
+ * Defaults to `true`.
72
+ */
73
+ disableSubmitWhilePending?: boolean;
74
+ /** Called with the validated values after a successful submit. */
75
+ onSubmit: (values: FormValues<TField>, form: HTMLFormElement) => void | Promise<void>;
76
+ /** Reset the form after a successful onSubmit. */
77
+ resetOnSuccess?: boolean;
78
+ }
79
+ /** Handle returned by `bindForm`. Calling it directly unsubscribes (same as before). */
80
+ export interface BindFormHandle<TField extends string> {
81
+ (): void;
82
+ /** Reads and trims the current values of all schema fields from the form. */
83
+ getValues(): FormValues<TField>;
84
+ /** Writes a value into the form field with the given name. */
85
+ setValue(field: TField, value: string): void;
86
+ /** Shows (or, if `message` is undefined, hides) the error for `[data-error-for="<field>"]`. */
87
+ setError(field: TField, message: string | undefined): void;
88
+ /** Resets the form, clears all displayed errors and recaptures dirty/touched state. */
89
+ reset(): void;
90
+ /** Returns a snapshot of the current form state (values/errors/touched/dirty/isSubmitting). */
91
+ getState(): FormState<TField>;
92
+ /** Calls `callback` whenever `field`'s value changes. Returns an unsubscribe function. */
93
+ watch(field: TField, callback: (value: string, values: FormValues<TField>) => void): () => void;
94
+ }
95
+ /**
96
+ * Subscribes to a form's submit event: prevents the page reload, validates fields
97
+ * against the schema (required/pattern/minLength/maxLength/min/max/validate, then
98
+ * an optional `resolver`) and calls onSubmit with the collected values.
99
+ * Submitting via Enter works out of the box (default <form> behavior).
100
+ *
101
+ * If `validateOn` is set, fields are additionally validated on "blur" or "input"
102
+ * and per-field errors are shown in `[data-error-for="<field>"]` elements.
103
+ *
104
+ * While `onSubmit` is pending, `[type="submit"]` elements are disabled (unless
105
+ * `disableSubmitWhilePending` is `false`) and `isSubmitting` is reported via `onStateChange`.
106
+ *
107
+ * Returns a handle: call it to unsubscribe, or use `getValues`/`setValue`/`setError`/
108
+ * `reset`/`getState`/`watch`.
109
+ */
110
+ export declare function bindForm<TField extends string>(form: HTMLFormElement, options: BindFormOptions<TField>): BindFormHandle<TField>;
package/dist/index.js CHANGED
@@ -1,30 +1,127 @@
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);
1
+ //#region src/index.ts
2
+ function e(e, r) {
3
+ let i = Object.keys(r.schema), a = {}, o = {}, s = {}, c = !1, l = (e, t) => {
4
+ let n = r.schema[e];
5
+ if (n.required && !t) return n.required;
6
+ if (t) {
7
+ if (n.pattern && !n.pattern.value.test(t)) return n.pattern.message;
8
+ if (n.minLength && t.length < n.minLength.value) return n.minLength.message;
9
+ if (n.maxLength && t.length > n.maxLength.value) return n.maxLength.message;
10
+ if (n.min || n.max) {
11
+ let e = Number(t);
12
+ if (!Number.isNaN(e)) {
13
+ if (n.min && e < n.min.value) return n.min.message;
14
+ if (n.max && e > n.max.value) return n.max.message;
15
+ }
16
+ }
17
+ return n.validate?.(t) || void 0;
18
+ }
19
+ }, u = (t) => e.querySelector(`[data-error-for="${t}"]`), d = (e, t) => {
20
+ a[e] = t;
21
+ let n = u(e);
22
+ n && (t ? (n.textContent = t, n.removeAttribute("hidden")) : n.setAttribute("hidden", ""));
23
+ }, f = (t) => String(new FormData(e).get(t) ?? "").trim(), p = () => {
24
+ let e = {};
25
+ for (let t of i) e[t] = f(t);
26
+ return e;
27
+ }, m = () => {
28
+ s = p();
29
+ };
30
+ m();
31
+ let h = () => {
32
+ let e = {};
33
+ for (let t of i) e[t] = f(t) !== s[t];
34
+ return e;
35
+ }, g = () => {
36
+ if (!r.onStateChange) return;
37
+ let e = h();
38
+ r.onStateChange({
39
+ values: p(),
40
+ errors: { ...a },
41
+ touched: { ...o },
42
+ dirty: e,
43
+ isDirty: i.some((t) => e[t]),
44
+ isSubmitting: c
45
+ });
46
+ }, _ = (t) => {
47
+ let n = e.querySelectorAll("[type=\"submit\"]");
48
+ for (let e of n) e.disabled = t;
49
+ }, v = async () => {
50
+ let e = p(), t = {};
51
+ for (let n of i) t[n] = l(n, e[n]);
52
+ if (r.resolver) {
53
+ let n = await r.resolver(e);
54
+ for (let e of i) !t[e] && n[e] && (t[e] = n[e]);
55
+ }
56
+ let n;
57
+ for (let e of i) d(e, t[e]), !n && t[e] && (n = t[e]);
58
+ return {
59
+ values: e,
60
+ firstError: n
61
+ };
62
+ }, y = () => {
63
+ for (let e of i) d(e, void 0);
64
+ n(r.errorElement);
65
+ }, b = (a) => {
66
+ a.preventDefault(), (async () => {
67
+ let { values: a, firstError: s } = await v();
68
+ if (g(), s) {
69
+ t(r.errorElement, s);
70
+ return;
71
+ }
72
+ n(r.errorElement), c = !0, r.disableSubmitWhilePending !== !1 && _(!0), g();
73
+ try {
74
+ if (await r.onSubmit(a, e), r.resetOnSuccess) {
75
+ e.reset(), y();
76
+ for (let e of i) o[e] = !1;
77
+ m();
78
+ }
79
+ } finally {
80
+ c = !1, r.disableSubmitWhilePending !== !1 && _(!1), g();
81
+ }
82
+ })();
83
+ }, x = (e) => {
84
+ let t = e.target;
85
+ if (!(t instanceof HTMLElement)) return;
86
+ let n = t.getAttribute("name");
87
+ !n || !i.includes(n) || (o[n] = !0, d(n, l(n, f(n))), g());
88
+ };
89
+ e.addEventListener("submit", b), r.validateOn && e.addEventListener(r.validateOn, x, !0);
90
+ let S = (() => {
91
+ e.removeEventListener("submit", b), r.validateOn && e.removeEventListener(r.validateOn, x, !0);
92
+ });
93
+ return S.getValues = p, S.setValue = (t, n) => {
94
+ let r = e.elements.namedItem(t);
95
+ (r instanceof HTMLInputElement || r instanceof HTMLTextAreaElement || r instanceof HTMLSelectElement) && (r.value = n), g();
96
+ }, S.setError = (e, t) => {
97
+ d(e, t), g();
98
+ }, S.reset = () => {
99
+ e.reset(), y();
100
+ for (let e of i) o[e] = !1;
101
+ m(), g();
102
+ }, S.getState = () => {
103
+ let e = h();
104
+ return {
105
+ values: p(),
106
+ errors: { ...a },
107
+ touched: { ...o },
108
+ dirty: e,
109
+ isDirty: i.some((t) => e[t]),
110
+ isSubmitting: c
111
+ };
112
+ }, S.watch = (t, n) => {
113
+ let r = (e) => {
114
+ let r = e.target;
115
+ r instanceof HTMLElement && r.getAttribute("name") === t && n(f(t), p());
116
+ };
117
+ return e.addEventListener("input", r), () => e.removeEventListener("input", r);
118
+ }, S;
21
119
  }
22
- function f(e, t) {
23
- e && (e.textContent = t, e.removeAttribute("hidden"));
120
+ function t(e, t) {
121
+ e && (e.textContent = t, e.removeAttribute("hidden"));
24
122
  }
25
- function o(e) {
26
- e && e.setAttribute("hidden", "");
123
+ function n(e) {
124
+ e && e.setAttribute("hidden", "");
27
125
  }
28
- export {
29
- m as bindForm
30
- };
126
+ //#endregion
127
+ export { e as bindForm };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chepchik/bind-form",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Tiny dependency-free form binding helper: submit handling, validation schema and error display.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -12,17 +12,23 @@
12
12
  "import": "./dist/index.js"
13
13
  }
14
14
  },
15
- "files": ["dist"],
15
+ "files": [
16
+ "dist"
17
+ ],
16
18
  "sideEffects": false,
17
19
  "scripts": {
18
20
  "build": "vite build",
19
21
  "dev": "vite build --watch"
20
22
  },
21
- "keywords": ["form", "validation", "spa"],
23
+ "keywords": [
24
+ "form",
25
+ "validation",
26
+ "spa"
27
+ ],
22
28
  "license": "MIT",
23
29
  "devDependencies": {
24
- "typescript": "^5.6.0",
25
- "vite": "^6.0.0",
26
- "vite-plugin-dts": "^4.3.0"
30
+ "typescript": "^6.0.3",
31
+ "vite": "^8.0.16",
32
+ "vite-plugin-dts": "^5.0.2"
27
33
  }
28
34
  }