@coxy/react-validator 2.0.6 → 3.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/README.md CHANGED
@@ -1,28 +1,30 @@
1
- ### React Validator
2
-  
1
+ # @Coxy/react-validator
3
2
 
4
- [![MIT License](https://img.shields.io/apm/l/atomic-design-ui.svg?)](https://github.com/dsshard/react-validator/blob/master/LICENSE)
5
- [![Travis CI](https://travis-ci.org/dsshard/react-validator.svg?branch=master)](https://travis-ci.org/dsshard/react-validator)
6
- [![CodeCov](https://codecov.io/gh/dsshard/react-validator/branch/master/graph/badge.svg)](https://codecov.io/gh/dsshard/react-validator)
7
- [![Coverage Status](https://coveralls.io/repos/github/dsshard/react-validator/badge.svg?branch=master)](https://coveralls.io/github/dsshard/react-validator?branch=master)
8
- [![dependencies Status](https://david-dm.org/dsshard/react-validator/status.svg)](https://david-dm.org/dsshard/react-validator)
9
- [![Maintainability](https://api.codeclimate.com/v1/badges/a30e71d313f2d8bdd6b1/maintainability)](https://codeclimate.com/github/dsshard/react-validator/maintainability)
10
- [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@coxy/react-validator)](https://bundlephobia.com/result?p=@coxy/react-validator)
11
- [![GitHub Release](https://img.shields.io/github/release/dsshard/react-validator.svg?style=flat)]()
3
+ ---
12
4
 
5
+ # Simple React Form Validation
13
6
 
14
- Simple React form validation.
7
+ @Coxy/react-validator provides a simple and flexible way to validate forms in React.
15
8
 
16
- Data validation on the **Node JS** side, is also supported.
9
+ > Supports data validation both **in-browser** and **on Node.js**.
17
10
 
11
+ > Requires React **\>=16.3**.
18
12
 
19
- Need react **>=16.3**
13
+ ---
20
14
 
21
- # Example
15
+ # Installation
22
16
 
23
- See more examples [here](example/example.tsx)
17
+ ```bash
18
+ npm install @coxy/react-validator
19
+ # or
20
+ yarn add @coxy/react-validator
21
+ ```
22
+
23
+ ---
24
+
25
+ # Quick Start Example
24
26
 
25
- ```jsx
27
+ ```tsx
26
28
  import React, { useState } from 'react';
27
29
  import { ValidatorWrapper, rules, ValidatorField } from '@coxy/react-validator';
28
30
 
@@ -34,174 +36,197 @@ const handleSubmit = () => {
34
36
  console.log(isValid, message, errors);
35
37
  return;
36
38
  }
37
- // Success
39
+ alert('Form is valid!');
38
40
  };
39
41
 
40
- export default () => {
41
- const [email, handleChange] = useState('');
42
+ export default function Example() {
43
+ const [email, setEmail] = useState('');
42
44
 
43
45
  return (
44
46
  <ValidatorWrapper ref={validator}>
45
-
46
47
  <ValidatorField value={email} rules={rules.email}>
47
48
  {({ isValid, message }) => (
48
49
  <>
49
- <input value={email} onChange={({ target: { value } }) => handleChange(value)} />
50
- {!isValid && <div>{message}</div>}
50
+ <input value={email} onChange={({ target: { value } }) => setEmail(value)} />
51
+ {!isValid && <div style={{ color: 'red' }}>{message}</div>}
51
52
  </>
52
53
  )}
53
54
  </ValidatorField>
54
55
 
55
- <ValidatorField value={email} rules={rules.email}>
56
- <input value={email} onChange={({ target: { value } }) => handleChange(value)} />
57
- </ValidatorField>
58
-
59
- {/* This is also possible :) */}
60
- <ValidatorField value={email} rules={rules.email} />
61
-
62
56
  <button onClick={handleSubmit} type="button">
63
57
  Submit
64
58
  </button>
65
-
66
59
  </ValidatorWrapper>
67
60
  );
68
- };
61
+ }
69
62
  ```
70
63
 
71
- See more examples [here](example/example.tsx)
72
- &nbsp;
73
- # Rules
64
+ More examples available [here](example/example.tsx).
65
+
66
+ ---
74
67
 
75
- You can create your own rules for validation, with your own error messages
68
+ # Built-in Validation Rules
76
69
 
70
+ Create your own rules easily, or use the built-in ones:
77
71
 
78
72
  ```javascript
79
73
  const rules = {
80
- email: [{
81
- rule: value => value !== '' && value.length > 0,
82
- message: 'Value is required',
83
- }, {
84
- rule: value => value.indexOf('@') > -1,
85
- message: '@ is required',
86
- }]
87
- }
74
+ email: [
75
+ { rule: value => value.trim() !== '', message: 'Value is required' },
76
+ { rule: value => value.includes('@'), message: '@ is required' },
77
+ ],
78
+ password: [
79
+ { rule: value => value.length >= 6, message: 'Password must be at least 6 characters' },
80
+ ],
81
+ notEmpty: [
82
+ { rule: value => !!value && value.trim() !== '', message: 'Field cannot be empty' },
83
+ ],
84
+ boolean: [
85
+ { rule: value => typeof value === 'boolean', message: 'Must be a boolean value' },
86
+ ],
87
+ min: (min) => ([
88
+ { rule: value => Number(value) >= min, message: `Must be at least ${min}` },
89
+ ]),
90
+ max: (max) => ([
91
+ { rule: value => Number(value) <= max, message: `Must be at most ${max}` },
92
+ ]),
93
+ length: (min, max) => ([
94
+ { rule: value => value.length >= min, message: `Must be at least ${min} characters` },
95
+ ...(max ? [{ rule: value => value.length <= max, message: `Must be at most ${max} characters` }] : [])
96
+ ]),
97
+ };
88
98
  ```
89
99
 
90
- This component has a default set of rules that you can use right away:
100
+ | Name | Type | Description |
101
+ |-------------|----------|-----------------------------------------------------------|
102
+ | email | Array | Validate non-empty email with regex check. |
103
+ | password | Array | Validate non-empty password with min length. |
104
+ | notEmpty | Array | Check if a string is not empty. |
105
+ | boolean | Array | Ensure a boolean value is present. |
106
+ | min(n) | Function | Validate number is >= `n`. |
107
+ | max(n) | Function | Validate number is <= `n`. |
108
+ | length(a,b) | Function | Validate string length is between `a` and `b` (optional). |
91
109
 
92
- | ****name**** | **Type** | **description** |
93
- |--------------|----------|-------------------------------------------------------------------------|
94
- | email | | Check email for empty string and regexp |
95
- | password | | Check password for empty string and length |
96
- | notEmpty | | Check if the string is not empty |
97
- | boolean | | Will check that the value is present |
98
- | min | function | min\(3\) \-> Check the number |
99
- | max | function | max\(5\) \-> Check the number |
100
- | length | function | length\(3, 5\) \-> Check string length \(second parameter is optional\) |
110
+ ---
101
111
 
102
- &nbsp;
112
+ # React API
103
113
 
104
- # Api for React
114
+ ## `<ValidatorWrapper />` Props
105
115
 
106
- #### ValidatorWrapper props
116
+ | Name | Default | Required | Description |
117
+ |------------------|---------|----------|----------------------------------------------------|
118
+ | ref | null | No | React ref or useRef for control. |
119
+ | stopAtFirstError | false | No | Stop validating after the first error. |
107
120
 
108
- | **name** | **default** | **required** | **description** |
109
- |------------------|-------------|--------------|--------------------------------------------------------|
110
- | ref | null | no | React\.ref or useRef |
111
- | stopAtFirstError | false | no | The validator will stop checking after the first error |
121
+ ## `<ValidatorField />` Props
112
122
 
113
- &nbsp;
114
- #### ValidatorField props
123
+ | Name | Default | Required | Description |
124
+ |----------|-----------|----------|---------------------------------------|
125
+ | value | undefined | Yes | Value to validate. |
126
+ | rules | [] | Yes | Validation rules array. |
127
+ | required | true | No | Whether the field is required. |
128
+ | id | null | No | ID for the field (for manual access). |
115
129
 
116
- | ****name**** | ****default**** | ****required**** | **description** |
117
- |--------------|-----------------|------------------|-------------------------------|
118
- | value | undefined | yes | Value for validation |
119
- | rules | \[\] | yes | Array of rules for validation |
120
- | required | true | no | The field will be required |
121
- | id | null | no | ID for get field |
130
+ ## `useValidator`
122
131
 
123
- &nbsp;
124
- # React api useValidator
132
+ Validate a value directly in your component:
125
133
 
126
- ```javascript
134
+ ```tsx
135
+ import { useValidator, rules } from '@coxy/react-validator';
127
136
 
128
- const [isValid, { errors }] = useValidator('test value', rules.email)
129
- console.log(isValid, errors) // false
137
+ const [isValid, { errors }] = useValidator('test@example.com', rules.email);
130
138
 
139
+ console.log(isValid); // true or false
140
+ console.log(errors); // array of error messages
131
141
  ```
132
142
 
133
- &nbsp;
134
- # Api for inline validation
143
+ ---
135
144
 
136
- #### Validator constructor parameters
145
+ # Validator Class (Node.js / Manual Usage)
137
146
 
138
- | **name** | **default** | **required** | **description** |
139
- |------------------|-------------|--------------|--------------------------------------------------------|
140
- | stopAtFirstError | false | no | The validator will stop checking after the first error |
147
+ Use it server-side or in custom flows.
141
148
 
142
- &nbsp;
143
- #### Validator.addField()
149
+ ## Validator Constructor Options
144
150
 
145
- Adds a field for validation
151
+ | Name | Default | Required | Description |
152
+ |------------------|---------|----------|------------------------------------------------------|
153
+ | stopAtFirstError | false | No | Stop validating after first error across all fields. |
146
154
 
147
- ```javascript
148
- import { Validator } from '@coxy/react-validator';
155
+ ## Methods
156
+
157
+ ### `.addField()`
149
158
 
159
+ ```javascript
150
160
  const validator = new Validator({ stopAtFirstError: true });
161
+
151
162
  const field = validator.addField({
152
- rules: rules.password,
153
- value: '',
163
+ rules: rules.password,
164
+ value: '12345',
154
165
  });
155
166
  ```
156
- &nbsp;
157
- #### Validator.getField()
158
167
 
159
- Returns the field by ID
168
+ ### `.getField(id)`
160
169
 
161
170
  ```javascript
162
- import { Validator } from '@coxy/react-validator';
171
+ const field = validator.getField('password-field');
172
+ console.log(field);
173
+ ```
163
174
 
164
- const validator = new Validator({ stopAtFirstError: true });
165
- const field = validator.addField({
166
- rules: rules.password,
167
- value: '',
168
- id: 'test-field-name'
169
- });
170
- console.log(validator.getField('test-field-name')) // Field Class
175
+ ### `.removeField(field)`
176
+
177
+ ```javascript
178
+ validator.removeField(field);
171
179
  ```
172
- &nbsp;
173
- #### Validator.removeField()
174
180
 
175
- Removes a previously added field
181
+ ### `.validate()`
182
+
183
+ ```javascript
184
+ const { isValid, message, errors } = validator.validate();
185
+ console.log(isValid, errors);
186
+ ```
176
187
 
188
+ ## Full Server-Side Example
177
189
 
178
190
  ```javascript
179
- import { Validator } from '@coxy/react-validator';
191
+ import { Validator, rules } from '@coxy/react-validator';
180
192
 
181
- const validator = new Validator({ stopAtFirstError: true });
182
- const field = validator.addField({
183
- rules: rules.password,
184
- value: '',
185
- id: 'test-field-name'
193
+ const validator = new Validator();
194
+
195
+ validator.addField({
196
+ id: 'email',
197
+ rules: rules.email,
198
+ value: 'test@domain.com',
186
199
  });
187
200
 
188
- validator.removeField(field);
189
- console.log(validator.getField('test-field-name')) // null
201
+ validator.addField({
202
+ id: 'password',
203
+ rules: rules.password,
204
+ value: '1234567',
205
+ });
206
+
207
+ const result = validator.validate();
208
+
209
+ if (result.isValid) {
210
+ console.log('Validation passed!');
211
+ } else {
212
+ console.error('Validation failed:', result.errors);
213
+ }
190
214
  ```
191
215
 
192
- &nbsp;
193
- #### Validator.validate()
216
+ ---
194
217
 
195
- Validates all added fields
218
+ # License
196
219
 
197
- ```javascript
198
- import { Validator } from '@coxy/react-validator';
220
+ MIT © [Dsshard](https://github.com/dsshard)
199
221
 
200
- const validator = new Validator({ stopAtFirstError: true });
201
- const field = validator.addField({
202
- rules: rules.password,
203
- value: '',
204
- });
222
+ ---
223
+
224
+ # Notes
225
+
226
+ - Lightweight, flexible, easy to integrate.
227
+ - Server-side and client-side validation supported.
228
+ - Create custom rules for different scenarios.
229
+ - Easy to add dynamic validation logic.
230
+
231
+ > **Fun Fact:** Early validation of user inputs in a form can reduce backend server load by up to **40%** compared to server-only validation!
205
232
 
206
- console.log(validator.validate());
207
- ```
package/biome.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "formatter": {
3
+ "enabled": true,
4
+ "indentStyle": "space",
5
+ "indentWidth": 2,
6
+ "lineWidth": 120,
7
+ "formatWithErrors": false,
8
+ "ignore": ["**/*.min.js"]
9
+ },
10
+ "javascript": {
11
+ "formatter": {
12
+ "quoteStyle": "single",
13
+ "semicolons": "asNeeded",
14
+ "trailingCommas": "all"
15
+ }
16
+ },
17
+ "linter": {
18
+ "enabled": true,
19
+ "rules": {
20
+ "recommended": true
21
+ }
22
+ },
23
+ "json": {
24
+ "formatter": {
25
+ "indentStyle": "space",
26
+ "indentWidth": 2
27
+ },
28
+ "linter": {
29
+ "enabled": true
30
+ }
31
+ }
32
+ }
@@ -0,0 +1,116 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { ReactNode, Component, RefObject } from 'react';
3
+
4
+ type Value = any;
5
+ type Fn$1 = (validity: Validity, value: Value) => ReactNode;
6
+ interface Props {
7
+ rules?: ValidatorRules;
8
+ required?: boolean;
9
+ value?: Value;
10
+ id?: string | number;
11
+ children?: ReactNode | Fn$1;
12
+ unregisterField: (val: Value) => void;
13
+ registerField: (val: Value) => void;
14
+ customErrors: Array<Validity>;
15
+ }
16
+ declare function ValidatorField(props: Omit<Props, 'registerField' | 'unregisterField' | 'customErrors'>): react_jsx_runtime.JSX.Element;
17
+
18
+ type Fn = (value: Value) => string;
19
+ interface ValidatorRule {
20
+ rule: (value: Value) => boolean;
21
+ message: string | Fn;
22
+ }
23
+ interface ErrorMessage {
24
+ message: string;
25
+ isValid: boolean;
26
+ }
27
+ interface Validity {
28
+ message: string;
29
+ isValid: boolean;
30
+ errors?: ErrorMessage[];
31
+ id?: string | number;
32
+ }
33
+ interface FieldParams {
34
+ value: Value;
35
+ rules: ValidatorRules;
36
+ required?: boolean;
37
+ id?: string | number;
38
+ }
39
+
40
+ type ValidatorRules = ValidatorRule[];
41
+ declare const rules: {
42
+ notEmpty: {
43
+ rule: (value: any) => boolean;
44
+ message: string;
45
+ }[];
46
+ bool: {
47
+ rule: (value: any) => boolean;
48
+ message: string;
49
+ }[];
50
+ password: {
51
+ rule: (value: any) => boolean;
52
+ message: string;
53
+ }[];
54
+ email: {
55
+ rule: (value: any) => boolean;
56
+ message: string;
57
+ }[];
58
+ min: (min: any) => {
59
+ rule: (value: any) => boolean;
60
+ message: string;
61
+ }[];
62
+ max: (max: any) => {
63
+ rule: (value: any) => boolean;
64
+ message: string;
65
+ }[];
66
+ length: (min: any, max?: any) => {
67
+ rule: (value: any) => boolean;
68
+ message: string;
69
+ }[];
70
+ };
71
+
72
+ declare class Field {
73
+ private rules;
74
+ private required;
75
+ private value;
76
+ id: string | number;
77
+ constructor({ rules, required, value, id }: FieldParams);
78
+ validate(): Validity;
79
+ }
80
+ interface ValidatorParams {
81
+ stopAtFirstError: boolean;
82
+ }
83
+ declare class Validator {
84
+ private fields;
85
+ private params;
86
+ constructor(params?: ValidatorParams);
87
+ addField(params: FieldParams): Field;
88
+ removeField(field: Field): void;
89
+ getField(id: Field['id']): Field;
90
+ validate(): Validity;
91
+ }
92
+
93
+ interface ComponentProps {
94
+ children?: ReactNode;
95
+ stopAtFirstError?: boolean;
96
+ ref?: RefObject<ValidatorWrapper>;
97
+ }
98
+ declare class ValidatorWrapper extends Component<ComponentProps> {
99
+ fields: any[];
100
+ state: {
101
+ customErrors: any[];
102
+ };
103
+ constructor(props: any);
104
+ componentWillUnmount(): void;
105
+ registerField(field: any): void;
106
+ unregisterField(field: any): void;
107
+ getField(id: any): Field | null;
108
+ setCustomError(customError: Validity): void;
109
+ clearCustomErrors(): void;
110
+ validate(): Validity;
111
+ render(): ReactNode;
112
+ }
113
+
114
+ declare function useValidator(value: Value, rules: ValidatorRules): [boolean, Pick<Validity, 'message' | 'errors'>];
115
+
116
+ export { type ErrorMessage, type FieldParams, Validator, ValidatorField, type ValidatorRule, ValidatorWrapper, type Validity, rules, useValidator };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,116 @@
1
- export { rules } from './rules';
2
- export { ValidatorField } from './validator-field';
3
- export { ValidatorWrapper } from './validator-wrapper';
4
- export { Validator } from './validator';
5
- export { useValidator } from './use-validator';
6
- export * from './types';
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { ReactNode, Component, RefObject } from 'react';
3
+
4
+ type Value = any;
5
+ type Fn$1 = (validity: Validity, value: Value) => ReactNode;
6
+ interface Props {
7
+ rules?: ValidatorRules;
8
+ required?: boolean;
9
+ value?: Value;
10
+ id?: string | number;
11
+ children?: ReactNode | Fn$1;
12
+ unregisterField: (val: Value) => void;
13
+ registerField: (val: Value) => void;
14
+ customErrors: Array<Validity>;
15
+ }
16
+ declare function ValidatorField(props: Omit<Props, 'registerField' | 'unregisterField' | 'customErrors'>): react_jsx_runtime.JSX.Element;
17
+
18
+ type Fn = (value: Value) => string;
19
+ interface ValidatorRule {
20
+ rule: (value: Value) => boolean;
21
+ message: string | Fn;
22
+ }
23
+ interface ErrorMessage {
24
+ message: string;
25
+ isValid: boolean;
26
+ }
27
+ interface Validity {
28
+ message: string;
29
+ isValid: boolean;
30
+ errors?: ErrorMessage[];
31
+ id?: string | number;
32
+ }
33
+ interface FieldParams {
34
+ value: Value;
35
+ rules: ValidatorRules;
36
+ required?: boolean;
37
+ id?: string | number;
38
+ }
39
+
40
+ type ValidatorRules = ValidatorRule[];
41
+ declare const rules: {
42
+ notEmpty: {
43
+ rule: (value: any) => boolean;
44
+ message: string;
45
+ }[];
46
+ bool: {
47
+ rule: (value: any) => boolean;
48
+ message: string;
49
+ }[];
50
+ password: {
51
+ rule: (value: any) => boolean;
52
+ message: string;
53
+ }[];
54
+ email: {
55
+ rule: (value: any) => boolean;
56
+ message: string;
57
+ }[];
58
+ min: (min: any) => {
59
+ rule: (value: any) => boolean;
60
+ message: string;
61
+ }[];
62
+ max: (max: any) => {
63
+ rule: (value: any) => boolean;
64
+ message: string;
65
+ }[];
66
+ length: (min: any, max?: any) => {
67
+ rule: (value: any) => boolean;
68
+ message: string;
69
+ }[];
70
+ };
71
+
72
+ declare class Field {
73
+ private rules;
74
+ private required;
75
+ private value;
76
+ id: string | number;
77
+ constructor({ rules, required, value, id }: FieldParams);
78
+ validate(): Validity;
79
+ }
80
+ interface ValidatorParams {
81
+ stopAtFirstError: boolean;
82
+ }
83
+ declare class Validator {
84
+ private fields;
85
+ private params;
86
+ constructor(params?: ValidatorParams);
87
+ addField(params: FieldParams): Field;
88
+ removeField(field: Field): void;
89
+ getField(id: Field['id']): Field;
90
+ validate(): Validity;
91
+ }
92
+
93
+ interface ComponentProps {
94
+ children?: ReactNode;
95
+ stopAtFirstError?: boolean;
96
+ ref?: RefObject<ValidatorWrapper>;
97
+ }
98
+ declare class ValidatorWrapper extends Component<ComponentProps> {
99
+ fields: any[];
100
+ state: {
101
+ customErrors: any[];
102
+ };
103
+ constructor(props: any);
104
+ componentWillUnmount(): void;
105
+ registerField(field: any): void;
106
+ unregisterField(field: any): void;
107
+ getField(id: any): Field | null;
108
+ setCustomError(customError: Validity): void;
109
+ clearCustomErrors(): void;
110
+ validate(): Validity;
111
+ render(): ReactNode;
112
+ }
113
+
114
+ declare function useValidator(value: Value, rules: ValidatorRules): [boolean, Pick<Validity, 'message' | 'errors'>];
115
+
116
+ export { type ErrorMessage, type FieldParams, Validator, ValidatorField, type ValidatorRule, ValidatorWrapper, type Validity, rules, useValidator };
package/dist/index.js CHANGED
@@ -1,28 +1,2 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.useValidator = exports.Validator = exports.ValidatorWrapper = exports.ValidatorField = exports.rules = void 0;
18
- var rules_1 = require("./rules");
19
- Object.defineProperty(exports, "rules", { enumerable: true, get: function () { return rules_1.rules; } });
20
- var validator_field_1 = require("./validator-field");
21
- Object.defineProperty(exports, "ValidatorField", { enumerable: true, get: function () { return validator_field_1.ValidatorField; } });
22
- var validator_wrapper_1 = require("./validator-wrapper");
23
- Object.defineProperty(exports, "ValidatorWrapper", { enumerable: true, get: function () { return validator_wrapper_1.ValidatorWrapper; } });
24
- var validator_1 = require("./validator");
25
- Object.defineProperty(exports, "Validator", { enumerable: true, get: function () { return validator_1.Validator; } });
26
- var use_validator_1 = require("./use-validator");
27
- Object.defineProperty(exports, "useValidator", { enumerable: true, get: function () { return use_validator_1.useValidator; } });
28
- __exportStar(require("./types"), exports);
1
+ 'use strict';var react=require('react'),jsxRuntime=require('react/jsx-runtime');var h=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,g={notEmpty:[{rule:t=>t!==""&&t.length>0,message:"Value is required"}],bool:[{rule:t=>!!t,message:"Value is required"}],password:[{rule:t=>t.length>0,message:"Password field cannot be empty"},{rule:t=>t.length>5,message:"Password field can not be less than 6 characters"}],email:[{rule:t=>!!t&&t!==""&&t.length!==0,message:"Email is required"},{rule:t=>h.test(String(t).toLowerCase()),message:"Email is invalid"}],min:t=>[{rule:e=>Number.parseFloat(e)>t,message:`The value must be greater than ${t}`}],max:t=>[{rule:e=>Number.parseFloat(e)<t,message:`The value must be smaller ${t}`}],length:(t,e)=>[{rule:r=>String(r).length>=t,message:`No less than ${t} symbols`},{rule:r=>e!==void 0?String(r).length<=e:true,message:`No more than ${e} symbols`}]};var d=react.createContext(null);var l=class{rules;required;value;id;constructor({rules:e,required:r,value:s,id:i}){this.rules=e,this.required=r,this.value=s,this.id=i;}validate(){let e=true,r="",{rules:s,value:i,required:n,id:m}=this,c=!i&&Number.parseFloat(i)!==0;if(!s.length||c&&n===false)return {isValid:e,message:r,id:m};for(let a of s)e&&(e=a.rule(i),e||(typeof a.message=="function"?r=a.message(i):r=a.message));return {isValid:e,message:r,id:m}}},o=class{fields;params;constructor(e){this.params=e||null,this.fields=[];}addField(e){let r=new l(e);return this.fields.push(r),r}removeField(e){let r=this.fields.indexOf(e);r>-1&&this.fields.splice(r,1);}getField(e){return this.fields.find(r=>r.id===e)||null}validate(){let e,s=this.fields.map(i=>this.params?.stopAtFirstError&&e&&e.isValid===false?null:(e=i.validate(),e)).filter(i=>i&&i.isValid===false);if(s.length){let{isValid:i,message:n}=s[0];return {isValid:i,message:n,errors:s}}return {isValid:true,message:""}}};var u=class extends react.Component{componentWillUnmount(){this.props.unregisterField(this);}componentDidMount(){this.props.registerField(this);}validate(){let e=this.props,r=e.customErrors.find(i=>i.id===e.id);return r||new l({rules:e.rules,required:e.required,value:e.value,id:e.id}).validate()}render(){let{children:e,value:r}=this.props,s=this.validate();return typeof e=="function"?e(s,r):e}};function F(t){return jsxRuntime.jsx(d.Consumer,{children:e=>jsxRuntime.jsx(u,{...t,customErrors:e.customErrors,registerField:e.registerField,unregisterField:e.unregisterField})})}var p=class extends react.Component{fields=[];state={customErrors:[]};constructor(e){super(e),this.registerField=this.registerField.bind(this),this.unregisterField=this.unregisterField.bind(this);}componentWillUnmount(){this.fields=[];}registerField(e){e&&!this.fields.includes(e)&&this.fields.push(e);}unregisterField(e){let r=this.fields.indexOf(e);r>-1&&this.fields.splice(r,1);}getField(e){return this.fields.find(r=>r.props.id===e)||null}setCustomError(e){this.setState({customErrors:[...this.state.customErrors,e]});}clearCustomErrors(){this.setState({customErrors:[]});}validate(){let e=new o({stopAtFirstError:this.props.stopAtFirstError});for(let r of this.fields)e.addField(r.props);return e.validate()}render(){return jsxRuntime.jsx(d.Provider,{value:{customErrors:this.state.customErrors,registerField:this.registerField,unregisterField:this.unregisterField},children:this.props.children})}};function x(t,e){let r=new o;r.addField({value:t,rules:e});let{isValid:s,...i}=r.validate();return [s,i]}exports.Validator=o;exports.ValidatorField=F;exports.ValidatorWrapper=p;exports.rules=g;exports.useValidator=x;//# sourceMappingURL=index.js.map
2
+ //# sourceMappingURL=index.js.map