form-validator-widget 1.0.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 ADDED
@@ -0,0 +1,8 @@
1
+ # Form Validator Widget
2
+
3
+ A reusable React form validation library with TypeScript support, animations, and advanced JavaScript concepts.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install form-validator-widget
@@ -0,0 +1,8 @@
1
+ import React from "react";
2
+ interface FormFieldProps extends React.InputHTMLAttributes<HTMLInputElement> {
3
+ label?: string;
4
+ errors?: string;
5
+ touched?: boolean;
6
+ }
7
+ export declare const FormField: React.FC<FormFieldProps>;
8
+ export {};
@@ -0,0 +1,4 @@
1
+ import React from "react";
2
+ import { FormValidatorProps } from "../types";
3
+ import '../styles/animations.module.css';
4
+ export declare const FormValidator: React.FC<FormValidatorProps>;
@@ -0,0 +1 @@
1
+ export declare function useDebounce<T extends (...args: any[]) => void>(fn: T, delay: number): T;
@@ -0,0 +1,7 @@
1
+ export { FormValidator } from './components/FormValidator';
2
+ export { FormField } from './components/FormField';
3
+ export { useDebounce } from './hooks/useDebounce';
4
+ export { validateField, validateForm } from './utils/validators';
5
+ export { throttle } from './utils/polyfills';
6
+ export type { ValidationRule, FormValidatorProps, FormState, ErrorState, FormContextValue } from './types';
7
+ import './utils/polyfills';
@@ -0,0 +1,222 @@
1
+ import { __assign, __rest } from 'tslib';
2
+ import React, { useRef, useCallback, useState } from 'react';
3
+
4
+ var validateField = function (value, rules) {
5
+ var _a, _b, _c, _d, _e;
6
+ if (!rules)
7
+ return undefined;
8
+ if (rules.required) {
9
+ var message = ((_a = rules.messages) === null || _a === void 0 ? void 0 : _a.required) || 'This field is required';
10
+ if (!value || value.trim() === '')
11
+ return message;
12
+ }
13
+ if (rules.email && value) {
14
+ var message = ((_b = rules.messages) === null || _b === void 0 ? void 0 : _b.email) || 'Please enter a valid email';
15
+ var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
16
+ if (!emailRegex.test(value))
17
+ return message;
18
+ }
19
+ if (rules.minLength && value) {
20
+ var message = ((_c = rules.messages) === null || _c === void 0 ? void 0 : _c.minLength) || "Must be at least ".concat(rules.minLength, " characters");
21
+ if (value.length < rules.minLength)
22
+ return message;
23
+ }
24
+ if (rules.maxLength && value) {
25
+ var message = ((_d = rules.messages) === null || _d === void 0 ? void 0 : _d.maxLength) || "Must be more than ".concat(rules.maxLength, " characters");
26
+ if (value.length > rules.maxLength)
27
+ return message;
28
+ }
29
+ if (rules.pattern && value) {
30
+ var message = ((_e = rules.messages) === null || _e === void 0 ? void 0 : _e.pattern) || 'Invalid format';
31
+ if (!rules.pattern.test(value))
32
+ return message;
33
+ }
34
+ if (rules.custom) {
35
+ return rules.custom(value);
36
+ }
37
+ return undefined;
38
+ };
39
+ var validateForm = function (values, rules) {
40
+ var errors = {};
41
+ Object.keys(rules).forEach(function (fieldName) {
42
+ var error = validateField(values[fieldName], rules[fieldName]);
43
+ if (error) {
44
+ errors[fieldName] = error;
45
+ }
46
+ });
47
+ return errors;
48
+ };
49
+
50
+ function useDebounce(fn, delay) {
51
+ var timeoutRef = useRef(undefined);
52
+ return useCallback((function () {
53
+ var args = [];
54
+ for (var _i = 0; _i < arguments.length; _i++) {
55
+ args[_i] = arguments[_i];
56
+ }
57
+ if (timeoutRef.current) {
58
+ clearTimeout(timeoutRef.current);
59
+ }
60
+ timeoutRef.current = setTimeout(function () {
61
+ fn.apply(void 0, args);
62
+ }, delay);
63
+ }), [fn, delay]);
64
+ }
65
+
66
+ function styleInject(css, ref) {
67
+ if ( ref === void 0 ) ref = {};
68
+ var insertAt = ref.insertAt;
69
+
70
+ if (!css || typeof document === 'undefined') { return; }
71
+
72
+ var head = document.head || document.getElementsByTagName('head')[0];
73
+ var style = document.createElement('style');
74
+ style.type = 'text/css';
75
+
76
+ if (insertAt === 'top') {
77
+ if (head.firstChild) {
78
+ head.insertBefore(style, head.firstChild);
79
+ } else {
80
+ head.appendChild(style);
81
+ }
82
+ } else {
83
+ head.appendChild(style);
84
+ }
85
+
86
+ if (style.styleSheet) {
87
+ style.styleSheet.cssText = css;
88
+ } else {
89
+ style.appendChild(document.createTextNode(css));
90
+ }
91
+ }
92
+
93
+ var css_248z = "@keyframes animations-module_shake__qVr3b{0%,to{transform:translateX(0)}10%,30%,50%,70%,90%{transform:translateX(-5px)}20%,40%,60%,80%{transform:translateX(5px)}}@keyframes animations-module_slideIn__lwqyK{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}@keyframes animations-module_gentlePulse__xvUHG{0%{box-shadow:0 0 0 0 rgba(59,130,246,.5)}70%{box-shadow:0 0 0 5px rgba(59,130,246,0)}to{box-shadow:0 0 0 0 rgba(59,130,246,0)}}.animations-module_form-validator-field__pirKM{transition:border-color .2s ease,box-shadow .2s ease}.animations-module_form-validator-field__pirKM:focus{animation:animations-module_gentlePulse__xvUHG 1.5s infinite;border-color:#3b82f6;outline:none}.animations-module_form-validator-field__pirKM.animations-module_error__Vq-ZO{animation:animations-module_shake__qVr3b .5s cubic-bezier(.36,.07,.19,.97) both;border-color:#ef4444}.animations-module_form-validator-error-message__h1Ge-{animation:animations-module_slideIn__lwqyK .2s ease-out;color:#ef4444;font-size:.875rem;margin-top:.25rem}.animations-module_form-validator-theme-dark__ySqnh .animations-module_form-validator-field__pirKM{background-color:#1f2937;border-color:#4b5563;color:#fff}.animations-module_form-validator-success__JkYav{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2310b981' stroke-width='2'%3E%3Cpath d='M20 6 9 17l-5-5'/%3E%3C/svg%3E\");background-position:right .5rem center;background-repeat:no-repeat;border-color:#10b981!important;padding-right:2rem}.animations-module_form-validator-field-container__9P7zl{margin-bottom:1rem}.animations-module_form-validator-label__O7u2s{color:#374151;display:block;font-size:.875rem;font-weight:500;margin-bottom:.25rem}.animations-module_form-validator-theme-dark__ySqn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ybS12YWxpZGF0b3ItZmllbGQtY29udGFpbmVyIHtcclxuICBtYXJnaW4tYm90dG9tOiAxcmVtO1xyXG59XHJcblxyXG4uZm9ybS12YWxpZGF0b3ItbGFiZWwge1xyXG4gIGRpc3BsYXk6IGJsb2NrO1xyXG4gIG1hcmdpbi1ib3R0b206IDAuMjVyZW07XHJcbiAgZm9udC1zaXplOiAwLjg3NXJlbTtcclxuICBmb250LXdlaWdodDogNTAwO1xyXG4gIGNvbG9yOiAjMzc0MTUxO1xyXG59XHJcblxyXG4uZm9ybS12YWxpZGF0b3ItdGhlbWUtZGFyayAuZm9ybS12YWxpZGF0b3ItbGFiZWwge1xyXG4gIGNvbG9yOiAjZTVlN2ViO1xyXG59XHJcblxyXG4uZm9ybS12YWxpZGF0b3ItaW5wdXQge1xyXG4gIGNvbXBvc2VzOiBmb3JtLXZhbGlkYXRvci1maWVsZDtcclxufSJdfQ== */";
94
+ styleInject(css_248z);
95
+
96
+ var FormValidator = function (_a) {
97
+ var children = _a.children, validationRules = _a.validationRules, onSubmit = _a.onSubmit, _b = _a.theme, theme = _b === void 0 ? 'light' : _b, _c = _a.customStyles, customStyles = _c === void 0 ? {} : _c, _d = _a.enableDebounce, enableDebounce = _d === void 0 ? true : _d, _e = _a.debounceDelay, debounceDelay = _e === void 0 ? 300 : _e;
98
+ var _f = useState({}), formValues = _f[0], setFormValues = _f[1];
99
+ var _g = useState({}), errors = _g[0], setErrors = _g[1];
100
+ var _h = useState({}), touched = _h[0], setTouched = _h[1];
101
+ var debouncedValidate = useDebounce(function (name, value) {
102
+ var error = validateField(value, validationRules[name]);
103
+ setErrors(function (prev) {
104
+ var _a;
105
+ return (__assign(__assign({}, prev), (_a = {}, _a[name] = error || '', _a)));
106
+ });
107
+ }, debounceDelay);
108
+ var handleChange = useCallback(function (e) {
109
+ var _a = e.target, name = _a.name, value = _a.value;
110
+ setFormValues(function (prev) {
111
+ var _a;
112
+ return (__assign(__assign({}, prev), (_a = {}, _a[name] = value, _a)));
113
+ });
114
+ if (enableDebounce) {
115
+ debouncedValidate(name, value);
116
+ }
117
+ else {
118
+ var error_1 = validateField(value, validationRules[name]);
119
+ setErrors(function (prev) {
120
+ var _a;
121
+ return (__assign(__assign({}, prev), (_a = {}, _a[name] = error_1 || '', _a)));
122
+ });
123
+ }
124
+ }, [enableDebounce, debouncedValidate, validationRules]);
125
+ var handleBlur = useCallback(function (e) {
126
+ var _a = e.target, name = _a.name, value = _a.value;
127
+ setTouched(function (prev) {
128
+ var _a;
129
+ return (__assign(__assign({}, prev), (_a = {}, _a[name] = true, _a)));
130
+ });
131
+ var error = validateField(value, validationRules[name]);
132
+ setErrors(function (prev) {
133
+ var _a;
134
+ return (__assign(__assign({}, prev), (_a = {}, _a[name] = error || '', _a)));
135
+ });
136
+ }, [validationRules]);
137
+ var handleSubmit = useCallback(function (e) {
138
+ e.preventDefault();
139
+ var formErrors = validateForm(formValues, validationRules);
140
+ setErrors(formErrors);
141
+ if (Object.keys(formErrors).length === 0) {
142
+ onSubmit(formValues);
143
+ }
144
+ }, [formValues, validationRules, onSubmit]);
145
+ var childrenWithProps = React.Children.map(children, function (child) {
146
+ if (React.isValidElement(child)) {
147
+ var element = child;
148
+ if (element.props.name) {
149
+ return React.cloneElement(child, {
150
+ onChange: handleChange,
151
+ onBlur: handleBlur,
152
+ value: formValues[element.props.name] || '',
153
+ className: "form-validator-field ".concat(errors[element.props.name] ? 'error' : '', " ").concat(touched[element.props.name] && !errors[element.props.name] ? 'form-validator-success' : '', " "),
154
+ style: customStyles[element.props.name],
155
+ 'data-theme': theme,
156
+ 'data-touched': touched[element.props.name],
157
+ 'data-error': !!errors[element.props.name]
158
+ });
159
+ }
160
+ }
161
+ return child;
162
+ });
163
+ var errorElements = Object.keys(errors).map(function (fieldName) { return (errors[fieldName] && (React.createElement("div", { key: fieldName, className: "form-validator-error-message", "data-field": fieldName }, errors[fieldName]))); });
164
+ return (React.createElement("form", { onSubmit: handleSubmit, className: "form-validator-theme-".concat(theme), style: customStyles.form, noValidate: true },
165
+ childrenWithProps,
166
+ errorElements,
167
+ React.createElement("button", { type: "submit" }, "Submit")));
168
+ };
169
+
170
+ var FormField = function (_a) {
171
+ var label = _a.label, errors = _a.errors, touched = _a.touched, _b = _a.className, className = _b === void 0 ? '' : _b, id = _a.id, props = __rest(_a, ["label", "errors", "touched", "className", "id"]);
172
+ var fieldId = id || props.name;
173
+ return (React.createElement("div", { className: "form-validator-field-container" },
174
+ label && (React.createElement("label", { htmlFor: fieldId, className: "form-validator-label" }, label)),
175
+ React.createElement("input", __assign({ id: fieldId, className: "form-validator-input ".concat(errors ? 'errors' : '', " ").concat(touched && !errors ? 'success' : '', " ").concat(className), "aria-invalid": !!errors, "aria-describedby": errors ? "".concat(fieldId, "-errors") : undefined }, props)),
176
+ errors && (React.createElement("div", { id: "".concat(fieldId, "-errors"), className: "form-validator-errors-message", role: "alert" }, errors))));
177
+ };
178
+
179
+ if (!Array.prototype.some) {
180
+ Array.prototype.some = function (callback, thisArg) {
181
+ for (var i = 0; i < this.length; i++) {
182
+ if (callback.call(thisArg, this[i], i, this)) {
183
+ return true;
184
+ }
185
+ }
186
+ return false;
187
+ };
188
+ }
189
+ if (!Array.prototype.every) {
190
+ Array.prototype.every = function (callback, thisArg) {
191
+ for (var i = 0; i < this.length; i++) {
192
+ if (!callback.call(thisArg, this[i], i, this)) {
193
+ return false;
194
+ }
195
+ }
196
+ return true;
197
+ };
198
+ }
199
+ if (!String.prototype.trim) {
200
+ String.prototype.trim = function () {
201
+ return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
202
+ };
203
+ }
204
+ var throttle = function (func, limit) {
205
+ var inThrottle;
206
+ var lastResult;
207
+ return function () {
208
+ var args = [];
209
+ for (var _i = 0; _i < arguments.length; _i++) {
210
+ args[_i] = arguments[_i];
211
+ }
212
+ if (!inThrottle) {
213
+ inThrottle = true;
214
+ lastResult = func.apply(this, args);
215
+ setTimeout(function () { return inThrottle = false; }, limit);
216
+ }
217
+ return lastResult;
218
+ };
219
+ };
220
+
221
+ export { FormField, FormValidator, throttle, useDebounce, validateField, validateForm };
222
+ //# sourceMappingURL=index.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm.js","sources":["../src/utils/validators.ts","../src/hooks/useDebounce.ts","../node_modules/style-inject/dist/style-inject.es.js","../src/components/FormValidator.tsx","../src/components/FormField.tsx","../src/utils/polyfills.ts"],"sourcesContent":["import { ValidationRule } from \"../types\";\r\n\r\nexport type ValidatorFn = (value: any) => string | undefined;\r\n\r\nexport const validateField = (\r\n value: any,\r\n rules?: ValidationRule\r\n): string | undefined => {\r\n if (!rules) return undefined;\r\n\r\n if(rules.required){\r\n const message = rules.messages?.required || 'This field is required';\r\n if(!value || value.trim() === '') return message;\r\n }\r\n\r\n if(rules.email && value){\r\n const message = rules.messages?.email || 'Please enter a valid email';\r\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\r\n if(!emailRegex.test(value)) return message;\r\n }\r\n\r\n if(rules.minLength && value){\r\n const message = rules.messages?.minLength || `Must be at least ${rules.minLength} characters`;\r\n if(value.length < rules.minLength) return message;\r\n }\r\n\r\n if(rules.maxLength && value){\r\n const message = rules.messages?.maxLength || `Must be more than ${rules.maxLength} characters`;\r\n if(value.length > rules.maxLength) return message;\r\n }\r\n\r\n if(rules.pattern && value){\r\n const message = rules.messages?.pattern || 'Invalid format';\r\n if(!rules.pattern.test(value)) return message;\r\n }\r\n\r\n if(rules.custom){\r\n return rules.custom(value);\r\n }\r\n\r\n return undefined;\r\n};\r\n\r\nexport const validateForm = (\r\n values: Record<string, any>,\r\n rules: Record<string, ValidationRule>\r\n): Record<string, string> => {\r\n const errors: Record<string, string> = {};\r\n\r\n Object.keys(rules).forEach(fieldName => {\r\n const error = validateField(values[fieldName], rules[fieldName]);\r\n if(error) {\r\n errors[fieldName] = error;\r\n }\r\n });\r\n\r\n return errors;\r\n};","import { useCallback, useRef } from \"react\";\r\n\r\nexport function useDebounce<T extends (...args: any[]) => void>(\r\n fn: T,\r\n delay: number\r\n): T {\r\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\r\n\r\n return useCallback(\r\n ((...args: any[]) => {\r\n if(timeoutRef.current) {\r\n clearTimeout(timeoutRef.current);\r\n }\r\n\r\n timeoutRef.current = setTimeout(() => {\r\n fn(...args);\r\n }, delay);\r\n }) as T,\r\n [fn, delay]\r\n );\r\n}","function styleInject(css, ref) {\n if ( ref === void 0 ) ref = {};\n var insertAt = ref.insertAt;\n\n if (!css || typeof document === 'undefined') { return; }\n\n var head = document.head || document.getElementsByTagName('head')[0];\n var style = document.createElement('style');\n style.type = 'text/css';\n\n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild);\n } else {\n head.appendChild(style);\n }\n } else {\n head.appendChild(style);\n }\n\n if (style.styleSheet) {\n style.styleSheet.cssText = css;\n } else {\n style.appendChild(document.createTextNode(css));\n }\n}\n\nexport default styleInject;\n","import React, {useState, useCallback} from \"react\";\r\nimport { FormValidatorProps, FormState, ErrorState } from \"../types\";\r\nimport { validateField, validateForm } from \"../utils/validators\";\r\nimport { useDebounce } from \"../hooks/useDebounce\";\r\nimport '../styles/animations.module.css';\r\n\r\nexport const FormValidator: React.FC<FormValidatorProps> = ({\r\n children,\r\n validationRules,\r\n onSubmit,\r\n theme = 'light',\r\n customStyles = {} ,\r\n enableDebounce = true,\r\n debounceDelay = 300\r\n}) => {\r\n const [formValues, setFormValues] = useState<FormState>({});\r\n const [errors, setErrors] = useState<ErrorState>({});\r\n const [touched, setTouched] = useState<Record<string, boolean>>({});\r\n\r\n const debouncedValidate = useDebounce((name: string, value: any) => {\r\n const error = validateField(value, validationRules[name]);\r\n setErrors(prev => ({...prev, [name]: error || ''}));\r\n }, debounceDelay);\r\n\r\n const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\r\n const {name, value} = e.target;\r\n\r\n setFormValues(prev => ({...prev, [name]: value }));\r\n\r\n if(enableDebounce) {\r\n debouncedValidate(name, value);\r\n } else {\r\n const error = validateField(value, validationRules[name]);\r\n setErrors(prev => ({...prev, [name]: error || '' }));\r\n }\r\n }, [enableDebounce, debouncedValidate, validationRules]);\r\n\r\n const handleBlur = useCallback((e: React.FocusEvent<HTMLInputElement>) => {\r\n const { name, value } = e.target;\r\n\r\n setTouched(prev => ({...prev, [name]: true }));\r\n\r\n\r\n const error = validateField(value, validationRules[name]);\r\n setErrors(prev => ({ ...prev, [name]: error || '' }));\r\n }, [validationRules]);\r\n\r\n const handleSubmit = useCallback((e: React.FormEvent) => {\r\n e.preventDefault();\r\n\r\n const formErrors = validateForm(formValues, validationRules);\r\n setErrors(formErrors);\r\n\r\n if(Object.keys(formErrors).length === 0){\r\n onSubmit(formValues);\r\n }\r\n }, [formValues, validationRules, onSubmit]);\r\n\r\n const childrenWithProps = React.Children.map(children, child => {\r\n if (React.isValidElement(child)) {\r\n const element = child as React.ReactElement<{ name?: string }>;\r\n\r\n if(element.props.name) {\r\n return React.cloneElement(child, {\r\n onChange: handleChange,\r\n onBlur: handleBlur,\r\n value: formValues[element.props.name] || '',\r\n className: `form-validator-field ${errors[element.props.name] ? 'error' : ''} ${touched[element.props.name] && !errors[element.props.name] ? 'form-validator-success' : ''} `,\r\n style: customStyles[element.props.name],\r\n 'data-theme': theme,\r\n 'data-touched': touched[element.props.name],\r\n 'data-error': !!errors[element.props.name]\r\n } as any);\r\n }\r\n }\r\n return child;\r\n });\r\n\r\n const errorElements = Object.keys(errors).map(fieldName => (\r\n errors[fieldName] && (\r\n <div key={fieldName} className=\"form-validator-error-message\" data-field={fieldName}>\r\n {errors[fieldName]}\r\n </div>\r\n )\r\n ));\r\n\r\n return (\r\n <form \r\n onSubmit={handleSubmit}\r\n className={`form-validator-theme-${theme}`}\r\n style={customStyles.form}\r\n noValidate\r\n >\r\n {childrenWithProps}\r\n {errorElements}\r\n <button type=\"submit\">Submit</button>\r\n </form>\r\n );\r\n}","import React from \"react\";\r\n\r\ninterface FormFieldProps extends React.InputHTMLAttributes<HTMLInputElement>{\r\n label?: string;\r\n errors?: string;\r\n touched?: boolean;\r\n}\r\n\r\nexport const FormField: React.FC<FormFieldProps> = ({\r\n label,\r\n errors,\r\n touched,\r\n className ='',\r\n id,\r\n ...props\r\n}) => {\r\n const fieldId = id || props.name;\r\n\r\n return (\r\n <div className=\"form-validator-field-container\">\r\n {label && (\r\n <label htmlFor={fieldId} className=\"form-validator-label\">\r\n {label}\r\n </label>\r\n )}\r\n\r\n <input id={fieldId} className={`form-validator-input ${errors ? 'errors' : ''} ${touched && !errors ? 'success' : ''} ${className}`}\r\n aria-invalid={!!errors}\r\n aria-describedby={errors ? `${fieldId}-errors` : undefined}\r\n {...props}/>\r\n\r\n {errors && (\r\n <div \r\n id={`${fieldId}-errors`}\r\n className=\"form-validator-errors-message\"\r\n role=\"alert\"\r\n >\r\n {errors}\r\n </div>\r\n )}\r\n </div>\r\n );\r\n};","\r\nif (!Array.prototype.some){\r\n Array.prototype.some = function<T>(\r\n this: T[],\r\n callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any\r\n ): boolean {\r\n for(let i=0; i< this.length; i++){\r\n if(callback.call(thisArg, this[i], i, this)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }; \r\n}\r\n\r\nif (!Array.prototype.every){\r\n Array.prototype.every = function<T>(\r\n this: T[],\r\n callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any\r\n ): boolean {\r\n for(let i=0; i< this.length; i++){\r\n if(!callback.call(thisArg, this[i], i, this)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n } as typeof Array.prototype.every; \r\n}\r\n\r\nif (!String.prototype.trim){\r\n String.prototype.trim = function(): string {\r\n return this.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\r\n };\r\n}\r\n\r\nexport const throttle = <T extends (...args: any[]) => any>(\r\n func: T,\r\n limit: number\r\n): T => {\r\n let inThrottle: boolean;\r\n let lastResult: ReturnType<T>;\r\n\r\n return function(this: any, ...args: any[]) {\r\n if(!inThrottle) {\r\n inThrottle = true;\r\n lastResult = func.apply(this, args);\r\n setTimeout(() => inThrottle = false, limit);\r\n }\r\n return lastResult;\r\n } as T;\r\n};\r\n"],"names":[],"mappings":";;;AAIa,IAAA,aAAa,GAAG,UACzB,KAAU,EACV,KAAsB,EAAA;;AAEtB,IAAA,IAAI,CAAC,KAAK;AAAE,QAAA,OAAO,SAAS,CAAC;AAE7B,IAAA,IAAG,KAAK,CAAC,QAAQ,EAAC;QACd,IAAM,OAAO,GAAG,CAAA,CAAA,EAAA,GAAA,KAAK,CAAC,QAAQ,MAAE,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,QAAQ,KAAI,wBAAwB,CAAC;QACrE,IAAG,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE;AAAE,YAAA,OAAO,OAAO,CAAC;KACpD;AAED,IAAA,IAAG,KAAK,CAAC,KAAK,IAAI,KAAK,EAAC;QACpB,IAAM,OAAO,GAAG,CAAA,CAAA,EAAA,GAAA,KAAK,CAAC,QAAQ,MAAE,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,KAAK,KAAI,4BAA4B,CAAC;QACtE,IAAM,UAAU,GAAG,4BAA4B,CAAC;AAChD,QAAA,IAAG,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC;AAAE,YAAA,OAAO,OAAO,CAAC;KAC9C;AAED,IAAA,IAAG,KAAK,CAAC,SAAS,IAAI,KAAK,EAAC;AACxB,QAAA,IAAM,OAAO,GAAG,CAAA,CAAA,EAAA,GAAA,KAAK,CAAC,QAAQ,MAAE,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,SAAS,KAAI,mBAAoB,CAAA,MAAA,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,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YACpC,UAAU,CAAC,YAAM,EAAA,OAAA,UAAU,GAAG,KAAK,CAAA,EAAA,EAAE,KAAK,CAAC,CAAC;SAC/C;AACD,QAAA,OAAO,UAAU,CAAC;AACtB,KAAM,CAAC;AACX;;;;","x_google_ignoreList":[2]}
package/dist/index.js ADDED
@@ -0,0 +1,229 @@
1
+ 'use strict';
2
+
3
+ var tslib = require('tslib');
4
+ var React = require('react');
5
+
6
+ var validateField = function (value, rules) {
7
+ var _a, _b, _c, _d, _e;
8
+ if (!rules)
9
+ return undefined;
10
+ if (rules.required) {
11
+ var message = ((_a = rules.messages) === null || _a === void 0 ? void 0 : _a.required) || 'This field is required';
12
+ if (!value || value.trim() === '')
13
+ return message;
14
+ }
15
+ if (rules.email && value) {
16
+ var message = ((_b = rules.messages) === null || _b === void 0 ? void 0 : _b.email) || 'Please enter a valid email';
17
+ var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
18
+ if (!emailRegex.test(value))
19
+ return message;
20
+ }
21
+ if (rules.minLength && value) {
22
+ var message = ((_c = rules.messages) === null || _c === void 0 ? void 0 : _c.minLength) || "Must be at least ".concat(rules.minLength, " characters");
23
+ if (value.length < rules.minLength)
24
+ return message;
25
+ }
26
+ if (rules.maxLength && value) {
27
+ var message = ((_d = rules.messages) === null || _d === void 0 ? void 0 : _d.maxLength) || "Must be more than ".concat(rules.maxLength, " characters");
28
+ if (value.length > rules.maxLength)
29
+ return message;
30
+ }
31
+ if (rules.pattern && value) {
32
+ var message = ((_e = rules.messages) === null || _e === void 0 ? void 0 : _e.pattern) || 'Invalid format';
33
+ if (!rules.pattern.test(value))
34
+ return message;
35
+ }
36
+ if (rules.custom) {
37
+ return rules.custom(value);
38
+ }
39
+ return undefined;
40
+ };
41
+ var validateForm = function (values, rules) {
42
+ var errors = {};
43
+ Object.keys(rules).forEach(function (fieldName) {
44
+ var error = validateField(values[fieldName], rules[fieldName]);
45
+ if (error) {
46
+ errors[fieldName] = error;
47
+ }
48
+ });
49
+ return errors;
50
+ };
51
+
52
+ function useDebounce(fn, delay) {
53
+ var timeoutRef = React.useRef(undefined);
54
+ return React.useCallback((function () {
55
+ var args = [];
56
+ for (var _i = 0; _i < arguments.length; _i++) {
57
+ args[_i] = arguments[_i];
58
+ }
59
+ if (timeoutRef.current) {
60
+ clearTimeout(timeoutRef.current);
61
+ }
62
+ timeoutRef.current = setTimeout(function () {
63
+ fn.apply(void 0, args);
64
+ }, delay);
65
+ }), [fn, delay]);
66
+ }
67
+
68
+ function styleInject(css, ref) {
69
+ if ( ref === void 0 ) ref = {};
70
+ var insertAt = ref.insertAt;
71
+
72
+ if (!css || typeof document === 'undefined') { return; }
73
+
74
+ var head = document.head || document.getElementsByTagName('head')[0];
75
+ var style = document.createElement('style');
76
+ style.type = 'text/css';
77
+
78
+ if (insertAt === 'top') {
79
+ if (head.firstChild) {
80
+ head.insertBefore(style, head.firstChild);
81
+ } else {
82
+ head.appendChild(style);
83
+ }
84
+ } else {
85
+ head.appendChild(style);
86
+ }
87
+
88
+ if (style.styleSheet) {
89
+ style.styleSheet.cssText = css;
90
+ } else {
91
+ style.appendChild(document.createTextNode(css));
92
+ }
93
+ }
94
+
95
+ var css_248z = "@keyframes animations-module_shake__qVr3b{0%,to{transform:translateX(0)}10%,30%,50%,70%,90%{transform:translateX(-5px)}20%,40%,60%,80%{transform:translateX(5px)}}@keyframes animations-module_slideIn__lwqyK{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}@keyframes animations-module_gentlePulse__xvUHG{0%{box-shadow:0 0 0 0 rgba(59,130,246,.5)}70%{box-shadow:0 0 0 5px rgba(59,130,246,0)}to{box-shadow:0 0 0 0 rgba(59,130,246,0)}}.animations-module_form-validator-field__pirKM{transition:border-color .2s ease,box-shadow .2s ease}.animations-module_form-validator-field__pirKM:focus{animation:animations-module_gentlePulse__xvUHG 1.5s infinite;border-color:#3b82f6;outline:none}.animations-module_form-validator-field__pirKM.animations-module_error__Vq-ZO{animation:animations-module_shake__qVr3b .5s cubic-bezier(.36,.07,.19,.97) both;border-color:#ef4444}.animations-module_form-validator-error-message__h1Ge-{animation:animations-module_slideIn__lwqyK .2s ease-out;color:#ef4444;font-size:.875rem;margin-top:.25rem}.animations-module_form-validator-theme-dark__ySqnh .animations-module_form-validator-field__pirKM{background-color:#1f2937;border-color:#4b5563;color:#fff}.animations-module_form-validator-success__JkYav{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2310b981' stroke-width='2'%3E%3Cpath d='M20 6 9 17l-5-5'/%3E%3C/svg%3E\");background-position:right .5rem center;background-repeat:no-repeat;border-color:#10b981!important;padding-right:2rem}.animations-module_form-validator-field-container__9P7zl{margin-bottom:1rem}.animations-module_form-validator-label__O7u2s{color:#374151;display:block;font-size:.875rem;font-weight:500;margin-bottom:.25rem}.animations-module_form-validator-theme-dark__ySqnh .animations-module_form-validator-label__O7u2s{color:#e5e7eb}\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImFuaW1hdGlvbnMubW9kdWxlLmNzcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFDQSwwQ0FDRSxNQUFXLHVCQUEwQixDQUNyQyxvQkFBMEIsMEJBQTZCLENBQ3ZELGdCQUFxQix5QkFBNEIsQ0FDbkQsQ0FFQSw0Q0FDRSxHQUNFLFNBQVUsQ0FDViwyQkFDRixDQUNBLEdBQ0UsU0FBVSxDQUNWLHVCQUNGLENBQ0YsQ0FFQSxnREFDRSxHQUFLLHNDQUE2QyxDQUNsRCxJQUFNLHVDQUE2QyxDQUNuRCxHQUFPLHFDQUEyQyxDQUNwRCxDQUVBLCtDQUNFLG9EQUNGLENBRUEscURBR0UsNERBQW9DLENBRHBDLG9CQUFxQixDQURyQixZQUdGLENBRUE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97
+
98
+ var FormValidator = function (_a) {
99
+ var children = _a.children, validationRules = _a.validationRules, onSubmit = _a.onSubmit, _b = _a.theme, theme = _b === void 0 ? 'light' : _b, _c = _a.customStyles, customStyles = _c === void 0 ? {} : _c, _d = _a.enableDebounce, enableDebounce = _d === void 0 ? true : _d, _e = _a.debounceDelay, debounceDelay = _e === void 0 ? 300 : _e;
100
+ var _f = React.useState({}), formValues = _f[0], setFormValues = _f[1];
101
+ var _g = React.useState({}), errors = _g[0], setErrors = _g[1];
102
+ var _h = React.useState({}), touched = _h[0], setTouched = _h[1];
103
+ var debouncedValidate = useDebounce(function (name, value) {
104
+ var error = validateField(value, validationRules[name]);
105
+ setErrors(function (prev) {
106
+ var _a;
107
+ return (tslib.__assign(tslib.__assign({}, prev), (_a = {}, _a[name] = error || '', _a)));
108
+ });
109
+ }, debounceDelay);
110
+ var handleChange = React.useCallback(function (e) {
111
+ var _a = e.target, name = _a.name, value = _a.value;
112
+ setFormValues(function (prev) {
113
+ var _a;
114
+ return (tslib.__assign(tslib.__assign({}, prev), (_a = {}, _a[name] = value, _a)));
115
+ });
116
+ if (enableDebounce) {
117
+ debouncedValidate(name, value);
118
+ }
119
+ else {
120
+ var error_1 = validateField(value, validationRules[name]);
121
+ setErrors(function (prev) {
122
+ var _a;
123
+ return (tslib.__assign(tslib.__assign({}, prev), (_a = {}, _a[name] = error_1 || '', _a)));
124
+ });
125
+ }
126
+ }, [enableDebounce, debouncedValidate, validationRules]);
127
+ var handleBlur = React.useCallback(function (e) {
128
+ var _a = e.target, name = _a.name, value = _a.value;
129
+ setTouched(function (prev) {
130
+ var _a;
131
+ return (tslib.__assign(tslib.__assign({}, prev), (_a = {}, _a[name] = true, _a)));
132
+ });
133
+ var error = validateField(value, validationRules[name]);
134
+ setErrors(function (prev) {
135
+ var _a;
136
+ return (tslib.__assign(tslib.__assign({}, prev), (_a = {}, _a[name] = error || '', _a)));
137
+ });
138
+ }, [validationRules]);
139
+ var handleSubmit = React.useCallback(function (e) {
140
+ e.preventDefault();
141
+ var formErrors = validateForm(formValues, validationRules);
142
+ setErrors(formErrors);
143
+ if (Object.keys(formErrors).length === 0) {
144
+ onSubmit(formValues);
145
+ }
146
+ }, [formValues, validationRules, onSubmit]);
147
+ var childrenWithProps = React.Children.map(children, function (child) {
148
+ if (React.isValidElement(child)) {
149
+ var element = child;
150
+ if (element.props.name) {
151
+ return React.cloneElement(child, {
152
+ onChange: handleChange,
153
+ onBlur: handleBlur,
154
+ value: formValues[element.props.name] || '',
155
+ className: "form-validator-field ".concat(errors[element.props.name] ? 'error' : '', " ").concat(touched[element.props.name] && !errors[element.props.name] ? 'form-validator-success' : '', " "),
156
+ style: customStyles[element.props.name],
157
+ 'data-theme': theme,
158
+ 'data-touched': touched[element.props.name],
159
+ 'data-error': !!errors[element.props.name]
160
+ });
161
+ }
162
+ }
163
+ return child;
164
+ });
165
+ var errorElements = Object.keys(errors).map(function (fieldName) { return (errors[fieldName] && (React.createElement("div", { key: fieldName, className: "form-validator-error-message", "data-field": fieldName }, errors[fieldName]))); });
166
+ return (React.createElement("form", { onSubmit: handleSubmit, className: "form-validator-theme-".concat(theme), style: customStyles.form, noValidate: true },
167
+ childrenWithProps,
168
+ errorElements,
169
+ React.createElement("button", { type: "submit" }, "Submit")));
170
+ };
171
+
172
+ var FormField = function (_a) {
173
+ var label = _a.label, errors = _a.errors, touched = _a.touched, _b = _a.className, className = _b === void 0 ? '' : _b, id = _a.id, props = tslib.__rest(_a, ["label", "errors", "touched", "className", "id"]);
174
+ var fieldId = id || props.name;
175
+ return (React.createElement("div", { className: "form-validator-field-container" },
176
+ label && (React.createElement("label", { htmlFor: fieldId, className: "form-validator-label" }, label)),
177
+ React.createElement("input", tslib.__assign({ id: fieldId, className: "form-validator-input ".concat(errors ? 'errors' : '', " ").concat(touched && !errors ? 'success' : '', " ").concat(className), "aria-invalid": !!errors, "aria-describedby": errors ? "".concat(fieldId, "-errors") : undefined }, props)),
178
+ errors && (React.createElement("div", { id: "".concat(fieldId, "-errors"), className: "form-validator-errors-message", role: "alert" }, errors))));
179
+ };
180
+
181
+ if (!Array.prototype.some) {
182
+ Array.prototype.some = function (callback, thisArg) {
183
+ for (var i = 0; i < this.length; i++) {
184
+ if (callback.call(thisArg, this[i], i, this)) {
185
+ return true;
186
+ }
187
+ }
188
+ return false;
189
+ };
190
+ }
191
+ if (!Array.prototype.every) {
192
+ Array.prototype.every = function (callback, thisArg) {
193
+ for (var i = 0; i < this.length; i++) {
194
+ if (!callback.call(thisArg, this[i], i, this)) {
195
+ return false;
196
+ }
197
+ }
198
+ return true;
199
+ };
200
+ }
201
+ if (!String.prototype.trim) {
202
+ String.prototype.trim = function () {
203
+ return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
204
+ };
205
+ }
206
+ var throttle = function (func, limit) {
207
+ var inThrottle;
208
+ var lastResult;
209
+ return function () {
210
+ var args = [];
211
+ for (var _i = 0; _i < arguments.length; _i++) {
212
+ args[_i] = arguments[_i];
213
+ }
214
+ if (!inThrottle) {
215
+ inThrottle = true;
216
+ lastResult = func.apply(this, args);
217
+ setTimeout(function () { return inThrottle = false; }, limit);
218
+ }
219
+ return lastResult;
220
+ };
221
+ };
222
+
223
+ exports.FormField = FormField;
224
+ exports.FormValidator = FormValidator;
225
+ exports.throttle = throttle;
226
+ exports.useDebounce = useDebounce;
227
+ exports.validateField = validateField;
228
+ exports.validateForm = validateForm;
229
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/utils/validators.ts","../src/hooks/useDebounce.ts","../node_modules/style-inject/dist/style-inject.es.js","../src/components/FormValidator.tsx","../src/components/FormField.tsx","../src/utils/polyfills.ts"],"sourcesContent":["import { ValidationRule } from \"../types\";\r\n\r\nexport type ValidatorFn = (value: any) => string | undefined;\r\n\r\nexport const validateField = (\r\n value: any,\r\n rules?: ValidationRule\r\n): string | undefined => {\r\n if (!rules) return undefined;\r\n\r\n if(rules.required){\r\n const message = rules.messages?.required || 'This field is required';\r\n if(!value || value.trim() === '') return message;\r\n }\r\n\r\n if(rules.email && value){\r\n const message = rules.messages?.email || 'Please enter a valid email';\r\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\r\n if(!emailRegex.test(value)) return message;\r\n }\r\n\r\n if(rules.minLength && value){\r\n const message = rules.messages?.minLength || `Must be at least ${rules.minLength} characters`;\r\n if(value.length < rules.minLength) return message;\r\n }\r\n\r\n if(rules.maxLength && value){\r\n const message = rules.messages?.maxLength || `Must be more than ${rules.maxLength} characters`;\r\n if(value.length > rules.maxLength) return message;\r\n }\r\n\r\n if(rules.pattern && value){\r\n const message = rules.messages?.pattern || 'Invalid format';\r\n if(!rules.pattern.test(value)) return message;\r\n }\r\n\r\n if(rules.custom){\r\n return rules.custom(value);\r\n }\r\n\r\n return undefined;\r\n};\r\n\r\nexport const validateForm = (\r\n values: Record<string, any>,\r\n rules: Record<string, ValidationRule>\r\n): Record<string, string> => {\r\n const errors: Record<string, string> = {};\r\n\r\n Object.keys(rules).forEach(fieldName => {\r\n const error = validateField(values[fieldName], rules[fieldName]);\r\n if(error) {\r\n errors[fieldName] = error;\r\n }\r\n });\r\n\r\n return errors;\r\n};","import { useCallback, useRef } from \"react\";\r\n\r\nexport function useDebounce<T extends (...args: any[]) => void>(\r\n fn: T,\r\n delay: number\r\n): T {\r\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\r\n\r\n return useCallback(\r\n ((...args: any[]) => {\r\n if(timeoutRef.current) {\r\n clearTimeout(timeoutRef.current);\r\n }\r\n\r\n timeoutRef.current = setTimeout(() => {\r\n fn(...args);\r\n }, delay);\r\n }) as T,\r\n [fn, delay]\r\n );\r\n}","function styleInject(css, ref) {\n if ( ref === void 0 ) ref = {};\n var insertAt = ref.insertAt;\n\n if (!css || typeof document === 'undefined') { return; }\n\n var head = document.head || document.getElementsByTagName('head')[0];\n var style = document.createElement('style');\n style.type = 'text/css';\n\n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild);\n } else {\n head.appendChild(style);\n }\n } else {\n head.appendChild(style);\n }\n\n if (style.styleSheet) {\n style.styleSheet.cssText = css;\n } else {\n style.appendChild(document.createTextNode(css));\n }\n}\n\nexport default styleInject;\n","import React, {useState, useCallback} from \"react\";\r\nimport { FormValidatorProps, FormState, ErrorState } from \"../types\";\r\nimport { validateField, validateForm } from \"../utils/validators\";\r\nimport { useDebounce } from \"../hooks/useDebounce\";\r\nimport '../styles/animations.module.css';\r\n\r\nexport const FormValidator: React.FC<FormValidatorProps> = ({\r\n children,\r\n validationRules,\r\n onSubmit,\r\n theme = 'light',\r\n customStyles = {} ,\r\n enableDebounce = true,\r\n debounceDelay = 300\r\n}) => {\r\n const [formValues, setFormValues] = useState<FormState>({});\r\n const [errors, setErrors] = useState<ErrorState>({});\r\n const [touched, setTouched] = useState<Record<string, boolean>>({});\r\n\r\n const debouncedValidate = useDebounce((name: string, value: any) => {\r\n const error = validateField(value, validationRules[name]);\r\n setErrors(prev => ({...prev, [name]: error || ''}));\r\n }, debounceDelay);\r\n\r\n const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\r\n const {name, value} = e.target;\r\n\r\n setFormValues(prev => ({...prev, [name]: value }));\r\n\r\n if(enableDebounce) {\r\n debouncedValidate(name, value);\r\n } else {\r\n const error = validateField(value, validationRules[name]);\r\n setErrors(prev => ({...prev, [name]: error || '' }));\r\n }\r\n }, [enableDebounce, debouncedValidate, validationRules]);\r\n\r\n const handleBlur = useCallback((e: React.FocusEvent<HTMLInputElement>) => {\r\n const { name, value } = e.target;\r\n\r\n setTouched(prev => ({...prev, [name]: true }));\r\n\r\n\r\n const error = validateField(value, validationRules[name]);\r\n setErrors(prev => ({ ...prev, [name]: error || '' }));\r\n }, [validationRules]);\r\n\r\n const handleSubmit = useCallback((e: React.FormEvent) => {\r\n e.preventDefault();\r\n\r\n const formErrors = validateForm(formValues, validationRules);\r\n setErrors(formErrors);\r\n\r\n if(Object.keys(formErrors).length === 0){\r\n onSubmit(formValues);\r\n }\r\n }, [formValues, validationRules, onSubmit]);\r\n\r\n const childrenWithProps = React.Children.map(children, child => {\r\n if (React.isValidElement(child)) {\r\n const element = child as React.ReactElement<{ name?: string }>;\r\n\r\n if(element.props.name) {\r\n return React.cloneElement(child, {\r\n onChange: handleChange,\r\n onBlur: handleBlur,\r\n value: formValues[element.props.name] || '',\r\n className: `form-validator-field ${errors[element.props.name] ? 'error' : ''} ${touched[element.props.name] && !errors[element.props.name] ? 'form-validator-success' : ''} `,\r\n style: customStyles[element.props.name],\r\n 'data-theme': theme,\r\n 'data-touched': touched[element.props.name],\r\n 'data-error': !!errors[element.props.name]\r\n } as any);\r\n }\r\n }\r\n return child;\r\n });\r\n\r\n const errorElements = Object.keys(errors).map(fieldName => (\r\n errors[fieldName] && (\r\n <div key={fieldName} className=\"form-validator-error-message\" data-field={fieldName}>\r\n {errors[fieldName]}\r\n </div>\r\n )\r\n ));\r\n\r\n return (\r\n <form \r\n onSubmit={handleSubmit}\r\n className={`form-validator-theme-${theme}`}\r\n style={customStyles.form}\r\n noValidate\r\n >\r\n {childrenWithProps}\r\n {errorElements}\r\n <button type=\"submit\">Submit</button>\r\n </form>\r\n );\r\n}","import React from \"react\";\r\n\r\ninterface FormFieldProps extends React.InputHTMLAttributes<HTMLInputElement>{\r\n label?: string;\r\n errors?: string;\r\n touched?: boolean;\r\n}\r\n\r\nexport const FormField: React.FC<FormFieldProps> = ({\r\n label,\r\n errors,\r\n touched,\r\n className ='',\r\n id,\r\n ...props\r\n}) => {\r\n const fieldId = id || props.name;\r\n\r\n return (\r\n <div className=\"form-validator-field-container\">\r\n {label && (\r\n <label htmlFor={fieldId} className=\"form-validator-label\">\r\n {label}\r\n </label>\r\n )}\r\n\r\n <input id={fieldId} className={`form-validator-input ${errors ? 'errors' : ''} ${touched && !errors ? 'success' : ''} ${className}`}\r\n aria-invalid={!!errors}\r\n aria-describedby={errors ? `${fieldId}-errors` : undefined}\r\n {...props}/>\r\n\r\n {errors && (\r\n <div \r\n id={`${fieldId}-errors`}\r\n className=\"form-validator-errors-message\"\r\n role=\"alert\"\r\n >\r\n {errors}\r\n </div>\r\n )}\r\n </div>\r\n );\r\n};","\r\nif (!Array.prototype.some){\r\n Array.prototype.some = function<T>(\r\n this: T[],\r\n callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any\r\n ): boolean {\r\n for(let i=0; i< this.length; i++){\r\n if(callback.call(thisArg, this[i], i, this)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }; \r\n}\r\n\r\nif (!Array.prototype.every){\r\n Array.prototype.every = function<T>(\r\n this: T[],\r\n callback: (value: T, index: number, array: T[]) => boolean, thisArg?: any\r\n ): boolean {\r\n for(let i=0; i< this.length; i++){\r\n if(!callback.call(thisArg, this[i], i, this)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n } as typeof Array.prototype.every; \r\n}\r\n\r\nif (!String.prototype.trim){\r\n String.prototype.trim = function(): string {\r\n return this.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\r\n };\r\n}\r\n\r\nexport const throttle = <T extends (...args: any[]) => any>(\r\n func: T,\r\n limit: number\r\n): T => {\r\n let inThrottle: boolean;\r\n let lastResult: ReturnType<T>;\r\n\r\n return function(this: any, ...args: any[]) {\r\n if(!inThrottle) {\r\n inThrottle = true;\r\n lastResult = func.apply(this, args);\r\n setTimeout(() => inThrottle = false, limit);\r\n }\r\n return lastResult;\r\n } as T;\r\n};\r\n"],"names":["useRef","useCallback","useState","__assign","__rest"],"mappings":";;;;;AAIa,IAAA,aAAa,GAAG,UACzB,KAAU,EACV,KAAsB,EAAA;;AAEtB,IAAA,IAAI,CAAC,KAAK;AAAE,QAAA,OAAO,SAAS,CAAC;AAE7B,IAAA,IAAG,KAAK,CAAC,QAAQ,EAAC;QACd,IAAM,OAAO,GAAG,CAAA,CAAA,EAAA,GAAA,KAA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EAAC;AAC7B,YAAA,IAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE;AAC1C,gBAAA,OAAO,KAAK,CAAC;aAChB;SACJ;AACD,QAAA,OAAO,IAAI,CAAC;AAChB,KAAiC,CAAC;AACtC,CAAC;AAED,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,EAAC;AACvB,IAAA,MAAM,CAAC,SAAS,CAAC,IAAI,GAAG,YAAA;QACpB,OAAO,IAAI,CAAC,OAAO,CAAC,oCAAoC,EAAE,EAAE,CAAC,CAAC;AAClE,KAAC,CAAC;AACN,CAAC;AAEY,IAAA,QAAQ,GAAG,UACpB,IAAO,EACP,KAAa,EAAA;AAEb,IAAA,IAAI,UAAmB,CAAC;AACxB,IAAA,IAAI,UAAyB,CAAC;IAE9B,OAAO,YAAA;QAAoB,IAAc,IAAA,GAAA,EAAA,CAAA;aAAd,IAAc,EAAA,GAAA,CAAA,EAAd,EAAc,GAAA,SAAA,CAAA,MAAA,EAAd,EAAc,EAAA,EAAA;YAAd,IAAc,CAAA,EAAA,CAAA,GAAA,SAAA,CAAA,EAAA,CAAA,CAAA;;QACrC,IAAG,CAAC,UAAU,EAAE;YACZ,UAAU,GAAG,IAAI,CAAC;YAClB,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YACpC,UAAU,CAAC,YAAM,EAAA,OAAA,UAAU,GAAG,KAAK,CAAA,EAAA,EAAE,KAAK,CAAC,CAAC;SAC/C;AACD,QAAA,OAAO,UAAU,CAAC;AACtB,KAAM,CAAC;AACX;;;;;;;;;","x_google_ignoreList":[2]}
@@ -0,0 +1,39 @@
1
+ export interface ValidationRule {
2
+ required?: boolean;
3
+ email?: boolean;
4
+ minLength?: number;
5
+ maxLength?: number;
6
+ pattern?: RegExp;
7
+ custom?: (value: any) => string | undefined;
8
+ messages?: {
9
+ required?: string;
10
+ email?: string;
11
+ minLength?: string;
12
+ maxLength?: string;
13
+ pattern?: string;
14
+ };
15
+ }
16
+ export interface FormValidatorProps {
17
+ children: React.ReactNode;
18
+ validationRules: Record<string, ValidationRule>;
19
+ onSubmit: (data: Record<string, any>) => void;
20
+ theme?: 'light' | 'dark' | Record<string, string>;
21
+ customStyles?: {
22
+ form?: React.CSSProperties;
23
+ [key: string]: React.CSSProperties | undefined;
24
+ };
25
+ enableDebounce?: boolean;
26
+ debounceDelay?: number;
27
+ }
28
+ export interface FormState {
29
+ [key: string]: any;
30
+ }
31
+ export interface ErrorState {
32
+ [key: string]: string;
33
+ }
34
+ export interface FormContextValue {
35
+ values: FormState;
36
+ errors: ErrorState;
37
+ handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
38
+ handleBlur: (e: React.FocusEvent<HTMLInputElement>) => void;
39
+ }
@@ -0,0 +1 @@
1
+ export declare const throttle: <T extends (...args: any[]) => any>(func: T, limit: number) => T;
@@ -0,0 +1,4 @@
1
+ import { ValidationRule } from "../types";
2
+ export type ValidatorFn = (value: any) => string | undefined;
3
+ export declare const validateField: (value: any, rules?: ValidationRule) => string | undefined;
4
+ export declare const validateForm: (values: Record<string, any>, rules: Record<string, ValidationRule>) => Record<string, string>;
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "form-validator-widget",
3
+ "version": "1.0.2",
4
+ "description": "A reusable form validation widget with animations and advanced JavaScript concepts",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.esm.js",
8
+ "types": "dist/index.d.ts",
9
+ "files": [
10
+ "dist",
11
+ "README.md"
12
+ ],
13
+ "scripts": {
14
+ "clean": "rimraf dist",
15
+ "build": "npm run clean && rollup -c",
16
+ "prepublishOnly": "npm run build",
17
+ "prepare": "npm run build",
18
+ "dev": "rollup -c -w"
19
+ },
20
+ "keywords": [
21
+ "react",
22
+ "form",
23
+ "validation",
24
+ "typescript",
25
+ "debounce",
26
+ "polyfill",
27
+ "animation"
28
+ ],
29
+ "author": "Syed Zaid",
30
+ "license": "MIT",
31
+ "peerDependencies": {
32
+ "react": ">=16.8.0",
33
+ "react-dom": ">=16.8.0"
34
+ },
35
+ "devDependencies": {
36
+ "@rollup/plugin-commonjs": "^25.0.0",
37
+ "@rollup/plugin-node-resolve": "^15.0.0",
38
+ "@rollup/plugin-typescript": "^11.0.0",
39
+ "@types/react": "^18.0.0",
40
+ "@types/react-dom": "^18.0.0",
41
+ "postcss": "^8.5.6",
42
+ "react": "^18.0.0",
43
+ "react-dom": "^18.0.0",
44
+ "rimraf": "^5.0.0",
45
+ "rollup": "^3.0.0",
46
+ "rollup-plugin-postcss": "^4.0.2",
47
+ "tslib": "^2.6.0",
48
+ "typescript": "^5.0.0"
49
+ }
50
+ }