ctrovalidate-react 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ctrotech
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,98 @@
1
+ # ctrovalidate-react
2
+
3
+ **Headless form validation hook for React.**
4
+
5
+ `ctrovalidate-react` provides `useCtrovalidate`, a single hook that wraps [`ctrovalidate-core`](https://www.npmjs.com/package/ctrovalidate-core)'s validation engine with reactive state, stable callbacks, and automatic abort handling for async rules.
6
+
7
+ [![npm version](https://img.shields.io/npm/v/ctrovalidate-react.svg)](https://www.npmjs.com/package/ctrovalidate-react)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
9
+
10
+ ---
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ npm install ctrovalidate-react ctrovalidate-core
16
+ ```
17
+
18
+ **Requirements:** React >=16.8.0
19
+
20
+ ---
21
+
22
+ ## Quick Start
23
+
24
+ ```tsx
25
+ import { useCtrovalidate } from 'ctrovalidate-react';
26
+
27
+ interface LoginForm { email: string; password: string; }
28
+
29
+ function LoginPage() {
30
+ const { values, errors, handleChange, handleBlur, validateForm, isValidating } =
31
+ useCtrovalidate<LoginForm>({
32
+ initialValues: { email: '', password: '' },
33
+ schema: { email: 'required|email', password: 'required|minLength:8' },
34
+ });
35
+
36
+ return (
37
+ <form onSubmit={async (e) => { e.preventDefault(); if (await validateForm()) { /* submit */ } }}>
38
+ <input value={values.email} onChange={(e) => handleChange('email', e.target.value)} onBlur={() => handleBlur('email')} />
39
+ {errors.email && <span>{errors.email}</span>}
40
+
41
+ <input type="password" value={values.password} onChange={(e) => handleChange('password', e.target.value)} onBlur={() => handleBlur('password')} />
42
+ {errors.password && <span>{errors.password}</span>}
43
+
44
+ <button type="submit" disabled={Object.values(isValidating).some(Boolean)}>Login</button>
45
+ </form>
46
+ );
47
+ }
48
+ ```
49
+
50
+ ---
51
+
52
+ ## API
53
+
54
+ ```typescript
55
+ const {
56
+ values, // Current form state
57
+ errors, // Partial<Record<keyof T, string>> — undefined if valid
58
+ isDirty, // Tracks touched fields
59
+ isValidating, // Tracks async validation in progress
60
+ handleChange, // Updates value, marks dirty, validates
61
+ handleBlur, // Marks dirty, validates (unless validateOnBlur: false)
62
+ validateField, // Validate a single field
63
+ validateForm, // Validate all fields
64
+ reset, // Reset to initial values, clear errors
65
+ } = useCtrovalidate<T>({
66
+ schema, // Required: field-to-rules mapping
67
+ initialValues, // Optional: form defaults (default: {})
68
+ validateOnBlur, // Optional: validate on blur (default: true)
69
+ customRules, // Optional: custom sync/async rule functions
70
+ aliases, // Optional: rule combination aliases
71
+ messages, // Optional: custom error messages
72
+ locale, // Optional: locale override for translator
73
+ });
74
+ ```
75
+
76
+ ---
77
+
78
+ ## Abort Handling
79
+
80
+ Each field has its own `AbortController`. Re-validating a field aborts any in-flight async rule. All controllers are aborted on unmount — no stale state updates.
81
+
82
+ ---
83
+
84
+ ## Related Packages
85
+
86
+ - **[ctrovalidate-core](https://www.npmjs.com/package/ctrovalidate-core)** — Validation engine
87
+ - **[ctrovalidate-browser](https://www.npmjs.com/package/ctrovalidate-browser)** — Vanilla JS DOM integration
88
+ - **[ctrovalidate-vue](https://www.npmjs.com/package/ctrovalidate-vue)** — Vue composable
89
+ - **[ctrovalidate-svelte](https://www.npmjs.com/package/ctrovalidate-svelte)** — Svelte stores
90
+ - **[ctrovalidate-next](https://www.npmjs.com/package/ctrovalidate-next)** — Next.js server actions
91
+
92
+ ---
93
+
94
+ ## License
95
+
96
+ MIT © [Ctrotech](https://github.com/ctrotech-tutor)
97
+
98
+ Full documentation: https://ctrovalidate.vercel.app
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react"),h=require("ctrovalidate-core");function q(v){const{initialValues:V={}}=v,[l,R]=t.useState(V),[E,b]=t.useState({}),[S,g]=t.useState({}),[k,y]=t.useState({}),o=t.useRef(v);t.useEffect(()=>{o.current=v});const C=t.useRef(l);C.current=l;const n=t.useRef({});t.useEffect(()=>()=>{Object.values(n.current).forEach(e=>e.abort())},[]);const u=t.useCallback(async(e,s)=>{var f;const r=e,a=o.current,i=a.schema[r];if(!i)return!0;const d=s!==void 0?s:C.current[e];n.current[r]&&n.current[r].abort(),n.current[r]=new AbortController,y(c=>({...c,[e]:!0}));try{const m=(f=(await h.validateAsync({[r]:d},{[r]:i},{customRules:a.customRules,aliases:a.aliases,messages:a.messages,locale:a.locale,signal:n.current[r].signal}))[r])==null?void 0:f.error;return b(p=>({...p,[e]:m||void 0})),!m}catch(c){return c instanceof Error&&c.name==="AbortError"||h.Logger.error(`Validation failed for ${r}:`,c),!1}finally{y(c=>({...c,[e]:!1}))}},[]),O=t.useCallback((e,s)=>{R(r=>({...r,[e]:s})),g(r=>({...r,[e]:!0})),u(e,s)},[u]),w=t.useCallback(e=>{g(s=>({...s,[e]:!0})),o.current.validateOnBlur!==!1&&u(e,C.current[e])},[u]),A=t.useCallback(async()=>{var i;const e=o.current,s=await h.validateAsync(l,e.schema,{customRules:e.customRules,aliases:e.aliases,messages:e.messages,locale:e.locale}),r={};let a=!0;for(const d in e.schema){const f=(i=s[d])==null?void 0:i.error;r[d]=f||void 0,f&&(a=!1)}return b(r),a},[l]),j=t.useCallback(e=>{R(e||o.current.initialValues||{}),b({}),g({}),y({})},[]);return{values:l,errors:E,isDirty:S,isValidating:k,handleChange:O,handleBlur:w,validateField:u,validateForm:A,reset:j}}exports.useCtrovalidate=q;
@@ -0,0 +1,34 @@
1
+ import { AsyncRuleLogic } from 'ctrovalidate-core';
2
+ import { RuleLogic } from 'ctrovalidate-core';
3
+ import { SchemaRule } from 'ctrovalidate-core';
4
+ import { ValidationSchema } from 'ctrovalidate-core';
5
+
6
+ /**
7
+ * useCtrovalidate hook for React.
8
+ * Headless validation logic designed for controlled inputs.
9
+ */
10
+ export declare function useCtrovalidate<T extends object = object>(options: UseCtrovalidateOptions<T>): UseCtrovalidateReturn<T>;
11
+
12
+ export declare interface UseCtrovalidateOptions<T extends object> {
13
+ schema: ValidationSchema;
14
+ initialValues?: T;
15
+ validateOnBlur?: boolean;
16
+ customRules?: Record<string, RuleLogic | AsyncRuleLogic>;
17
+ aliases?: Record<string, SchemaRule>;
18
+ messages?: Record<string, string>;
19
+ locale?: string;
20
+ }
21
+
22
+ export declare interface UseCtrovalidateReturn<T extends object> {
23
+ values: T;
24
+ errors: Partial<Record<keyof T, string>>;
25
+ isDirty: Partial<Record<keyof T, boolean>>;
26
+ isValidating: Partial<Record<keyof T, boolean>>;
27
+ handleChange: (name: keyof T, value: T[keyof T]) => void;
28
+ handleBlur: (name: keyof T) => void;
29
+ validateField: (name: keyof T, value?: T[keyof T]) => Promise<boolean>;
30
+ validateForm: () => Promise<boolean>;
31
+ reset: (newValues?: Partial<T>) => void;
32
+ }
33
+
34
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,85 @@
1
+ import { useState as g, useRef as b, useEffect as C, useCallback as f } from "react";
2
+ import { validateAsync as p, Logger as j } from "ctrovalidate-core";
3
+ function N(m) {
4
+ const { initialValues: w = {} } = m, [a, R] = g(w), [O, v] = g({}), [A, h] = g({}), [k, y] = g({}), n = b(m);
5
+ C(() => {
6
+ n.current = m;
7
+ });
8
+ const V = b(a);
9
+ V.current = a;
10
+ const c = b({});
11
+ C(() => () => {
12
+ Object.values(c.current).forEach((r) => r.abort());
13
+ }, []);
14
+ const l = f(
15
+ async (r, t) => {
16
+ var u;
17
+ const e = r, s = n.current, i = s.schema[e];
18
+ if (!i) return !0;
19
+ const d = t !== void 0 ? t : V.current[r];
20
+ c.current[e] && c.current[e].abort(), c.current[e] = new AbortController(), y((o) => ({ ...o, [r]: !0 }));
21
+ try {
22
+ const E = (u = (await p(
23
+ { [e]: d },
24
+ { [e]: i },
25
+ {
26
+ customRules: s.customRules,
27
+ aliases: s.aliases,
28
+ messages: s.messages,
29
+ locale: s.locale,
30
+ signal: c.current[e].signal
31
+ }
32
+ ))[e]) == null ? void 0 : u.error;
33
+ return v((S) => ({ ...S, [r]: E || void 0 })), !E;
34
+ } catch (o) {
35
+ return o instanceof Error && o.name === "AbortError" || j.error(`Validation failed for ${e}:`, o), !1;
36
+ } finally {
37
+ y((o) => ({ ...o, [r]: !1 }));
38
+ }
39
+ },
40
+ []
41
+ // No dependencies because we use optionsRef
42
+ ), B = f(
43
+ (r, t) => {
44
+ R((e) => ({ ...e, [r]: t })), h((e) => ({ ...e, [r]: !0 })), l(r, t);
45
+ },
46
+ [l]
47
+ ), D = f(
48
+ (r) => {
49
+ h((t) => ({ ...t, [r]: !0 })), n.current.validateOnBlur !== !1 && l(r, V.current[r]);
50
+ },
51
+ [l]
52
+ ), F = f(async () => {
53
+ var i;
54
+ const r = n.current, t = await p(a, r.schema, {
55
+ customRules: r.customRules,
56
+ aliases: r.aliases,
57
+ messages: r.messages,
58
+ locale: r.locale
59
+ }), e = {};
60
+ let s = !0;
61
+ for (const d in r.schema) {
62
+ const u = (i = t[d]) == null ? void 0 : i.error;
63
+ e[d] = u || void 0, u && (s = !1);
64
+ }
65
+ return v(e), s;
66
+ }, [a]), I = f((r) => {
67
+ R(
68
+ r || n.current.initialValues || {}
69
+ ), v({}), h({}), y({});
70
+ }, []);
71
+ return {
72
+ values: a,
73
+ errors: O,
74
+ isDirty: A,
75
+ isValidating: k,
76
+ handleChange: B,
77
+ handleBlur: D,
78
+ validateField: l,
79
+ validateForm: F,
80
+ reset: I
81
+ };
82
+ }
83
+ export {
84
+ N as useCtrovalidate
85
+ };
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "ctrovalidate-react",
3
+ "version": "1.0.0",
4
+ "description": "React adapter for Ctrovalidate.",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
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
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "scripts": {
20
+ "build": "vite build",
21
+ "dev": "vite build --watch",
22
+ "lint": "eslint .",
23
+ "test": "vitest run --passWithNoTests"
24
+ },
25
+ "homepage": "https://ctrovalidate.vercel.app/api/react",
26
+ "keywords": [
27
+ "ctrovalidate",
28
+ "validation",
29
+ "form-validation",
30
+ "react",
31
+ "hooks"
32
+ ],
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/ctrotech-tutor/ctrovalidate-react.git"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/ctrotech-tutor/ctrovalidate-react/issues"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "peerDependencies": {
44
+ "ctrovalidate-core": "^1.0.0",
45
+ "react": ">=16.8.0"
46
+ },
47
+ "devDependencies": {
48
+ "@eslint/js": "^9.39.2",
49
+ "@types/react": "^18.2.0",
50
+ "ctrovalidate-core": "^1.0.0",
51
+ "eslint": "^9.39.2",
52
+ "eslint-config-prettier": "^9.1.0",
53
+ "globals": "^17.2.0",
54
+ "prettier": "^3.1.1",
55
+ "react": "^18.2.0",
56
+ "vite": "^6.0.0",
57
+ "vite-plugin-dts": "^4.0.0",
58
+ "typescript": "^5.9.3",
59
+ "typescript-eslint": "^8.54.0",
60
+ "vitest": "^4.0.18"
61
+ }
62
+ }