@palakpreet/quick-validate 0.0.0-stage → 2.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 +17 -0
- package/README.md +309 -2
- package/package.json +35 -4
- package/src/index.js +509 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 quick-validate contributors
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,310 @@
|
|
|
1
|
-
#
|
|
1
|
+
# quick-validate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Lightweight, dependency-free JavaScript validation for common inputs and forms.**
|
|
4
|
+
|
|
5
|
+
`@palakpreet/quick-validate` is a collection of reusable JavaScript validation helpers designed to make validating user input simple, consistent, and easy to integrate into applications.
|
|
6
|
+
|
|
7
|
+
It provides individual validators, form and schema validation, custom validation rules, and commonly used Indian input format validations — all without external dependencies.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- Lightweight and dependency-free
|
|
12
|
+
- Written entirely in JavaScript
|
|
13
|
+
- Common input validators
|
|
14
|
+
- Indian-specific validators
|
|
15
|
+
- Password validation and strength checking
|
|
16
|
+
- Schema-based form validation
|
|
17
|
+
- Multiple validation rules per field
|
|
18
|
+
- Custom error messages
|
|
19
|
+
- Custom validation rules
|
|
20
|
+
- Nested object validation
|
|
21
|
+
- Array validation
|
|
22
|
+
- File metadata validation
|
|
23
|
+
- Simple and consistent error reporting
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npm install @palakpreet/quick-validate
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Quick Start
|
|
32
|
+
|
|
33
|
+
```js
|
|
34
|
+
import quickValidate from "@palakpreet/quick-validate";
|
|
35
|
+
|
|
36
|
+
console.log(quickValidate.isEmail("person@example.com"));
|
|
37
|
+
// true
|
|
38
|
+
|
|
39
|
+
console.log(quickValidate.isPAN("ABCDE1234F"));
|
|
40
|
+
// true
|
|
41
|
+
|
|
42
|
+
console.log(quickValidate.isIFSC("HDFC0001234"));
|
|
43
|
+
// true
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Validate Individual Values
|
|
47
|
+
|
|
48
|
+
Use the built-in validators directly:
|
|
49
|
+
|
|
50
|
+
```js
|
|
51
|
+
import {
|
|
52
|
+
isEmail,
|
|
53
|
+
isIndianPhone,
|
|
54
|
+
isIndianPinCode,
|
|
55
|
+
isStrongPassword,
|
|
56
|
+
isURL,
|
|
57
|
+
isPAN,
|
|
58
|
+
isGSTIN,
|
|
59
|
+
isIFSC,
|
|
60
|
+
isUPI
|
|
61
|
+
} from "@palakpreet/quick-validate";
|
|
62
|
+
|
|
63
|
+
console.log(isEmail("person@example.com"));
|
|
64
|
+
// true
|
|
65
|
+
|
|
66
|
+
console.log(isIndianPhone("9876543210"));
|
|
67
|
+
// true
|
|
68
|
+
|
|
69
|
+
console.log(isIndianPinCode("411001"));
|
|
70
|
+
// true
|
|
71
|
+
|
|
72
|
+
console.log(isStrongPassword("StrongPass@123"));
|
|
73
|
+
// true
|
|
74
|
+
|
|
75
|
+
console.log(isURL("https://example.com"));
|
|
76
|
+
// true
|
|
77
|
+
|
|
78
|
+
console.log(isPAN("ABCDE1234F"));
|
|
79
|
+
// true
|
|
80
|
+
|
|
81
|
+
console.log(isGSTIN("27ABCDE1234F1Z5"));
|
|
82
|
+
// true
|
|
83
|
+
|
|
84
|
+
console.log(isIFSC("HDFC0001234"));
|
|
85
|
+
// true
|
|
86
|
+
|
|
87
|
+
console.log(isUPI("person@upi"));
|
|
88
|
+
// true
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Individual validators return a boolean indicating whether the value passes the validation check.
|
|
92
|
+
|
|
93
|
+
## Validate a Value Using Rules
|
|
94
|
+
|
|
95
|
+
The `validate()` function allows you to combine multiple rules for a single value.
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
import { validate } from "@palakpreet/quick-validate";
|
|
99
|
+
|
|
100
|
+
const result = validate("bad-email", ["required", "email"]);
|
|
101
|
+
|
|
102
|
+
console.log(result);
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Output:
|
|
106
|
+
|
|
107
|
+
```js
|
|
108
|
+
{
|
|
109
|
+
valid: false,
|
|
110
|
+
errors: [
|
|
111
|
+
"Please enter a valid email address."
|
|
112
|
+
]
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Available Rules
|
|
117
|
+
|
|
118
|
+
Rules can be supplied as strings, arrays, rule objects, or custom functions.
|
|
119
|
+
|
|
120
|
+
```js
|
|
121
|
+
const result = validate("hello", [
|
|
122
|
+
"required",
|
|
123
|
+
{ name: "minLength", value: 3 }
|
|
124
|
+
]);
|
|
125
|
+
|
|
126
|
+
console.log(result.valid);
|
|
127
|
+
// true
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Supported parameter-based rules include:
|
|
131
|
+
|
|
132
|
+
| Rule | Description | Example |
|
|
133
|
+
|---|---|---|
|
|
134
|
+
| `minLength` | Minimum string length | `{ name: "minLength", value: 3 }` |
|
|
135
|
+
| `maxLength` | Maximum string length | `{ name: "maxLength", value: 20 }` |
|
|
136
|
+
| `min` | Minimum numeric value | `{ name: "min", value: 18 }` |
|
|
137
|
+
| `max` | Maximum numeric value | `{ name: "max", value: 100 }` |
|
|
138
|
+
| `oneOf` | Value must match one of the allowed values | `{ name: "oneOf", values: ["red", "blue"] }` |
|
|
139
|
+
| `matches` | Value must match a regular expression | `{ name: "matches", pattern: /^[A-Z]+$/ }` |
|
|
140
|
+
|
|
141
|
+
## Validate an Entire Form
|
|
142
|
+
|
|
143
|
+
`validateSchema()` validates multiple fields together and returns field-specific errors.
|
|
144
|
+
|
|
145
|
+
```js
|
|
146
|
+
import { validateSchema } from "@palakpreet/quick-validate";
|
|
147
|
+
|
|
148
|
+
const schema = {
|
|
149
|
+
name: ["required", { name: "minLength", value: 2 }],
|
|
150
|
+
email: ["required", "email"],
|
|
151
|
+
age: [{ name: "min", value: 18 }]
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const data = {
|
|
155
|
+
name: "A",
|
|
156
|
+
email: "bad-email",
|
|
157
|
+
age: 16
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const result = validateSchema(data, schema);
|
|
161
|
+
|
|
162
|
+
console.log(result.valid);
|
|
163
|
+
// false
|
|
164
|
+
|
|
165
|
+
console.log(result.errors);
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Example result:
|
|
169
|
+
|
|
170
|
+
```js
|
|
171
|
+
{
|
|
172
|
+
valid: false,
|
|
173
|
+
errors: {
|
|
174
|
+
name: ["..."],
|
|
175
|
+
email: ["..."],
|
|
176
|
+
age: ["..."]
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
Schema validation makes it possible to validate multiple fields and collect their errors in one operation.
|
|
182
|
+
|
|
183
|
+
## Custom Error Messages
|
|
184
|
+
|
|
185
|
+
You can provide your own messages for individual validation rules.
|
|
186
|
+
|
|
187
|
+
```js
|
|
188
|
+
const schema = {
|
|
189
|
+
email: {
|
|
190
|
+
rules: ["required", "email"],
|
|
191
|
+
messages: {
|
|
192
|
+
email: "Please enter a valid email address."
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
This allows error messages to be customized according to your application's needs.
|
|
199
|
+
|
|
200
|
+
## Custom Validation Rules
|
|
201
|
+
|
|
202
|
+
Add your own reusable validation rules using `addValidator()`.
|
|
203
|
+
|
|
204
|
+
```js
|
|
205
|
+
import {
|
|
206
|
+
addValidator,
|
|
207
|
+
validate
|
|
208
|
+
} from "@palakpreet/quick-validate";
|
|
209
|
+
|
|
210
|
+
addValidator("even", value => Number(value) % 2 === 0);
|
|
211
|
+
|
|
212
|
+
const result = validate(6, ["even"]);
|
|
213
|
+
|
|
214
|
+
console.log(result.valid);
|
|
215
|
+
// true
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
Custom rules can be reused throughout your application.
|
|
219
|
+
|
|
220
|
+
## Additional Validation Helpers
|
|
221
|
+
|
|
222
|
+
```js
|
|
223
|
+
import {
|
|
224
|
+
validateField,
|
|
225
|
+
validateArray,
|
|
226
|
+
validateNested,
|
|
227
|
+
validateObject,
|
|
228
|
+
isFileValid
|
|
229
|
+
} from "@palakpreet/quick-validate";
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
| Function | Description |
|
|
233
|
+
|---|---|
|
|
234
|
+
| `validateField(data, schema, field)` | Validates a specific field |
|
|
235
|
+
| `validateArray(value, rules, options)` | Validates array values and constraints |
|
|
236
|
+
| `validateNested(data, schema)` | Validates nested objects |
|
|
237
|
+
| `validateObject(data, validatorFunctions)` | Validates an object using custom validator functions |
|
|
238
|
+
| `isFileValid(file, options)` | Validates file metadata such as size and type |
|
|
239
|
+
|
|
240
|
+
## Available Validators
|
|
241
|
+
|
|
242
|
+
### General Validators
|
|
243
|
+
|
|
244
|
+
- Presence and required values
|
|
245
|
+
- Email addresses
|
|
246
|
+
- Phone numbers
|
|
247
|
+
- Postal codes
|
|
248
|
+
- Passwords and password strength
|
|
249
|
+
- URLs and domains
|
|
250
|
+
- UUIDs
|
|
251
|
+
- IPv4 and IPv6 addresses
|
|
252
|
+
- IP addresses
|
|
253
|
+
- Credit card numbers using the Luhn algorithm
|
|
254
|
+
- Dates and date-time values
|
|
255
|
+
- Usernames
|
|
256
|
+
- Slugs
|
|
257
|
+
- Hexadecimal colours
|
|
258
|
+
- Alphanumeric values
|
|
259
|
+
- Numeric values and integers
|
|
260
|
+
- JSON strings
|
|
261
|
+
|
|
262
|
+
### Indian-Specific Validators
|
|
263
|
+
|
|
264
|
+
- Indian mobile numbers
|
|
265
|
+
- Indian PIN codes
|
|
266
|
+
- PAN
|
|
267
|
+
- GSTIN format
|
|
268
|
+
- IFSC
|
|
269
|
+
- UPI IDs
|
|
270
|
+
- Indian vehicle registration numbers
|
|
271
|
+
- Bank account format
|
|
272
|
+
|
|
273
|
+
### Additional Helpers
|
|
274
|
+
|
|
275
|
+
- Confirm password
|
|
276
|
+
- Minimum and maximum length
|
|
277
|
+
- Numeric range
|
|
278
|
+
- Regular expression matching
|
|
279
|
+
- Allowed values
|
|
280
|
+
- Array validation
|
|
281
|
+
- File metadata validation
|
|
282
|
+
|
|
283
|
+
## Running Tests
|
|
284
|
+
|
|
285
|
+
This project uses Node.js's built-in test runner.
|
|
286
|
+
|
|
287
|
+
Run the test suite using:
|
|
288
|
+
|
|
289
|
+
```bash
|
|
290
|
+
npm test
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
## Requirements
|
|
294
|
+
|
|
295
|
+
- Node.js 18 or later
|
|
296
|
+
- JavaScript
|
|
297
|
+
- ES Modules support
|
|
298
|
+
|
|
299
|
+
## Important Notes
|
|
300
|
+
|
|
301
|
+
This package validates input formats and rules. It does not verify values against official databases.
|
|
302
|
+
|
|
303
|
+
- PAN and GSTIN validation checks format, not registration status.
|
|
304
|
+
- IFSC validation checks format, not whether a bank branch currently exists.
|
|
305
|
+
- Credit card validation checks the Luhn algorithm, not whether a card is active or authorized.
|
|
306
|
+
- File validation checks metadata. Uploaded files must still be inspected securely on the server.
|
|
307
|
+
|
|
308
|
+
## License
|
|
309
|
+
|
|
310
|
+
MIT License
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@palakpreet/quick-validate",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "A lightweight JavaScript validation library for forms, objects, and common inputs.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./src/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.js"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"src",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"test": "node --test",
|
|
18
|
+
"demo": "node demo/server.js"
|
|
19
|
+
},
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"validation",
|
|
25
|
+
"validator",
|
|
26
|
+
"javascript",
|
|
27
|
+
"forms",
|
|
28
|
+
"email",
|
|
29
|
+
"india",
|
|
30
|
+
"npm"
|
|
31
|
+
],
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "https://github.com/Palakpreet-Kaur-Bhullar/quick-validate-v2"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/Palakpreet-Kaur-Bhullar/quick-validate-v2/blob/main/README.md"
|
|
37
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
/** quick-validate v2 — lightweight JavaScript validators. */
|
|
2
|
+
const str = (v) => (typeof v === "string" ? v.trim() : "");
|
|
3
|
+
const plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
4
|
+
const custom = {};
|
|
5
|
+
|
|
6
|
+
export const isPresent = (v) =>
|
|
7
|
+
v !== null &&
|
|
8
|
+
v !== undefined &&
|
|
9
|
+
!(typeof v === "string" && !v.trim()) &&
|
|
10
|
+
!(Array.isArray(v) && !v.length);
|
|
11
|
+
export const isEmail = (v) => {
|
|
12
|
+
const s = str(v);
|
|
13
|
+
if (!s || s.length > 254 || /\s/.test(s)) return false;
|
|
14
|
+
const p = s.split("@");
|
|
15
|
+
if (p.length !== 2) return false;
|
|
16
|
+
const [local, domain] = p;
|
|
17
|
+
const labels = domain.split(".");
|
|
18
|
+
return (
|
|
19
|
+
!!local &&
|
|
20
|
+
local.length <= 64 &&
|
|
21
|
+
!local.startsWith(".") &&
|
|
22
|
+
!local.endsWith(".") &&
|
|
23
|
+
!local.includes("..") &&
|
|
24
|
+
/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+$/.test(local) &&
|
|
25
|
+
labels.length >= 2 &&
|
|
26
|
+
labels.every(
|
|
27
|
+
(x) =>
|
|
28
|
+
x.length <= 63 && /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(x),
|
|
29
|
+
) &&
|
|
30
|
+
/^[A-Za-z]{2,}$/.test(labels.at(-1))
|
|
31
|
+
);
|
|
32
|
+
};
|
|
33
|
+
export const isIndianPhone = (v, o = {}) => {
|
|
34
|
+
let s = str(v).replace(/[\s().-]/g, "");
|
|
35
|
+
if (!s) return false;
|
|
36
|
+
if (o.allowLandline) {
|
|
37
|
+
const t = s
|
|
38
|
+
.replace(/^\+91/, "")
|
|
39
|
+
.replace(/^0091/, "")
|
|
40
|
+
.replace(/^91(?=\d{10}$)/, "");
|
|
41
|
+
if (/^0?[1-9]\d{2,4}\d{6,8}$/.test(t)) return true;
|
|
42
|
+
}
|
|
43
|
+
if (!o.allowWithoutCountryCode && !/^\+91|^0091|^91/.test(s)) return false;
|
|
44
|
+
return /^[6-9]\d{9}$/.test(s.replace(/^\+91|^0091|^91/, ""));
|
|
45
|
+
};
|
|
46
|
+
export const isPhone = (v, country) =>
|
|
47
|
+
country?.toUpperCase() === "IN"
|
|
48
|
+
? isIndianPhone(v, { allowWithoutCountryCode: true })
|
|
49
|
+
: /^\+?[1-9]\d{7,14}$/.test(str(v).replace(/[\s().-]/g, ""));
|
|
50
|
+
export const isIndianPinCode = (v) => /^[1-9]\d{5}$/.test(str(v));
|
|
51
|
+
export const isPostalCode = (v, c) => {
|
|
52
|
+
const s = str(v),
|
|
53
|
+
k = String(c || "").toUpperCase();
|
|
54
|
+
if (["IN", "INDIA"].includes(k)) return isIndianPinCode(s);
|
|
55
|
+
if (["US", "USA"].includes(k)) return /^\d{5}(-\d{4})?$/.test(s);
|
|
56
|
+
if (["CA", "CANADA"].includes(k))
|
|
57
|
+
return /^[A-Z]\d[A-Z][ -]?\d[A-Z]\d$/i.test(s);
|
|
58
|
+
if (["GB", "UK"].includes(k))
|
|
59
|
+
return /^[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$/i.test(s);
|
|
60
|
+
return /^[A-Z0-9][A-Z0-9 -]{1,10}[A-Z0-9]$/i.test(s);
|
|
61
|
+
};
|
|
62
|
+
export const isStrongPassword = (v, o = {}) => {
|
|
63
|
+
const s = typeof v === "string" ? v : "";
|
|
64
|
+
return (
|
|
65
|
+
s.length >= (o.minLength ?? 8) &&
|
|
66
|
+
s.length <= (o.maxLength ?? 128) &&
|
|
67
|
+
(o.lowercase === false || /[a-z]/.test(s)) &&
|
|
68
|
+
(o.uppercase === false || /[A-Z]/.test(s)) &&
|
|
69
|
+
(o.number === false || /\d/.test(s)) &&
|
|
70
|
+
(o.symbol === false || /[^A-Za-z0-9\s]/.test(s)) &&
|
|
71
|
+
(o.noSpaces === false || !/\s/.test(s))
|
|
72
|
+
);
|
|
73
|
+
};
|
|
74
|
+
export const getPasswordStrength = (v) => {
|
|
75
|
+
const s = typeof v === "string" ? v : "";
|
|
76
|
+
const checks = {
|
|
77
|
+
length: s.length >= 8,
|
|
78
|
+
lowercase: /[a-z]/.test(s),
|
|
79
|
+
uppercase: /[A-Z]/.test(s),
|
|
80
|
+
number: /\d/.test(s),
|
|
81
|
+
symbol: /[^A-Za-z0-9\s]/.test(s),
|
|
82
|
+
noSpaces: !/\s/.test(s),
|
|
83
|
+
};
|
|
84
|
+
let score = Object.values(checks).filter(Boolean).length;
|
|
85
|
+
if (s.length >= 14) score++;
|
|
86
|
+
if (s.length < 8) score = Math.min(score, 1);
|
|
87
|
+
score = Math.min(4, score);
|
|
88
|
+
return {
|
|
89
|
+
score,
|
|
90
|
+
label: ["very-weak", "weak", "fair", "strong", "very-strong"][score],
|
|
91
|
+
checks,
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
export const isURL = (v, o = {}) => {
|
|
95
|
+
const s = str(v);
|
|
96
|
+
if (!s || /\s/.test(s)) return false;
|
|
97
|
+
try {
|
|
98
|
+
const u = new URL(/^[a-z][a-z\d+.-]*:/i.test(s) ? s : `https://${s}`);
|
|
99
|
+
return (
|
|
100
|
+
["http:", "https:"].includes(u.protocol) &&
|
|
101
|
+
(!o.requireHttps || u.protocol === "https:") &&
|
|
102
|
+
!!u.hostname &&
|
|
103
|
+
(o.allowLocalhost ||
|
|
104
|
+
!(u.hostname === "localhost" || !u.hostname.includes(".")))
|
|
105
|
+
);
|
|
106
|
+
} catch {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
export const isDomain = (v) => {
|
|
111
|
+
const s = str(v);
|
|
112
|
+
return (
|
|
113
|
+
!!s &&
|
|
114
|
+
s.length <= 253 &&
|
|
115
|
+
!s.includes("/") &&
|
|
116
|
+
!s.includes("://") &&
|
|
117
|
+
isURL(`https://${s}`)
|
|
118
|
+
);
|
|
119
|
+
};
|
|
120
|
+
export const isUUID = (v) =>
|
|
121
|
+
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
|
|
122
|
+
str(v),
|
|
123
|
+
);
|
|
124
|
+
export const isIPv4 = (v) => {
|
|
125
|
+
const p = str(v).split(".");
|
|
126
|
+
return (
|
|
127
|
+
p.length === 4 &&
|
|
128
|
+
p.every(
|
|
129
|
+
(x) =>
|
|
130
|
+
/^\d{1,3}$/.test(x) && +x <= 255 && (x === "0" || !x.startsWith("0")),
|
|
131
|
+
)
|
|
132
|
+
);
|
|
133
|
+
};
|
|
134
|
+
export const isIPv6 = (v) => {
|
|
135
|
+
const s = str(v);
|
|
136
|
+
if (!s.includes(":") || !/^[\da-f:]+$/i.test(s)) return false;
|
|
137
|
+
try {
|
|
138
|
+
new URL(`http://[${s}]/`);
|
|
139
|
+
return true;
|
|
140
|
+
} catch {
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
export const isIP = (v) => isIPv4(v) || isIPv6(v);
|
|
145
|
+
export const isCreditCard = (v) => {
|
|
146
|
+
const d = str(v).replace(/[\s-]/g, "");
|
|
147
|
+
if (!/^\d{13,19}$/.test(d)) return false;
|
|
148
|
+
let sum = 0,
|
|
149
|
+
twice = false;
|
|
150
|
+
for (let i = d.length - 1; i >= 0; i--) {
|
|
151
|
+
let n = +d[i];
|
|
152
|
+
if (twice && (n *= 2) > 9) n -= 9;
|
|
153
|
+
sum += n;
|
|
154
|
+
twice = !twice;
|
|
155
|
+
}
|
|
156
|
+
return sum % 10 === 0;
|
|
157
|
+
};
|
|
158
|
+
export const isDate = (v) => {
|
|
159
|
+
const s = str(v);
|
|
160
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return false;
|
|
161
|
+
const [y, m, d] = s.split("-").map(Number),
|
|
162
|
+
dt = new Date(Date.UTC(y, m - 1, d));
|
|
163
|
+
return (
|
|
164
|
+
dt.getUTCFullYear() === y &&
|
|
165
|
+
dt.getUTCMonth() === m - 1 &&
|
|
166
|
+
dt.getUTCDate() === d
|
|
167
|
+
);
|
|
168
|
+
};
|
|
169
|
+
export const isDateTime = (v) => {
|
|
170
|
+
const s = str(v);
|
|
171
|
+
return !!s && s.includes("T") && !Number.isNaN(new Date(s).getTime());
|
|
172
|
+
};
|
|
173
|
+
export const isUsername = (v, o = {}) => {
|
|
174
|
+
const s = str(v);
|
|
175
|
+
return (
|
|
176
|
+
s.length >= (o.minLength ?? 3) &&
|
|
177
|
+
s.length <= (o.maxLength ?? 20) &&
|
|
178
|
+
/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(s)
|
|
179
|
+
);
|
|
180
|
+
};
|
|
181
|
+
export const isSlug = (v) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(str(v));
|
|
182
|
+
export const isHexColor = (v, alpha = false) =>
|
|
183
|
+
new RegExp(
|
|
184
|
+
`^#(?:[0-9a-f]{3}|[0-9a-f]{6}${alpha ? "|[0-9a-f]{8}" : ""})$`,
|
|
185
|
+
"i",
|
|
186
|
+
).test(str(v));
|
|
187
|
+
export const isAlphanumeric = (v) => /^[A-Za-z0-9]+$/.test(str(v));
|
|
188
|
+
export const isNumeric = (v, o = {}) => {
|
|
189
|
+
const s = str(v);
|
|
190
|
+
return (
|
|
191
|
+
!!s &&
|
|
192
|
+
new RegExp(
|
|
193
|
+
`^${o.negative ? "-?" : ""}\\d${o.decimal === false ? "" : "(?:\\.\\d+)?"}$`,
|
|
194
|
+
).test(s)
|
|
195
|
+
);
|
|
196
|
+
};
|
|
197
|
+
export const isInteger = (v, o = {}) => {
|
|
198
|
+
const s = str(v);
|
|
199
|
+
if (!/^-?\d+$/.test(s)) return false;
|
|
200
|
+
const n = Number(s);
|
|
201
|
+
return (
|
|
202
|
+
Number.isSafeInteger(n) &&
|
|
203
|
+
(o.min === undefined || n >= o.min) &&
|
|
204
|
+
(o.max === undefined || n <= o.max)
|
|
205
|
+
);
|
|
206
|
+
};
|
|
207
|
+
export const isJSON = (v) => {
|
|
208
|
+
if (typeof v !== "string") return false;
|
|
209
|
+
try {
|
|
210
|
+
JSON.parse(v);
|
|
211
|
+
return true;
|
|
212
|
+
} catch {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
export const hasMinLength = (v, n) => typeof v === "string" && v.length >= n;
|
|
217
|
+
export const hasMaxLength = (v, n) => typeof v === "string" && v.length <= n;
|
|
218
|
+
export const isInRange = (v, min, max) =>
|
|
219
|
+
typeof v === "number" && Number.isFinite(v) && v >= min && v <= max;
|
|
220
|
+
export const matchesRegex = (v, r) => {
|
|
221
|
+
if (typeof v !== "string" || !(r instanceof RegExp)) return false;
|
|
222
|
+
r.lastIndex = 0;
|
|
223
|
+
return r.test(v);
|
|
224
|
+
};
|
|
225
|
+
export const isOneOf = (v, values) =>
|
|
226
|
+
Array.isArray(values) && values.includes(v);
|
|
227
|
+
export const isPAN = (v) => /^[A-Z]{5}\d{4}[A-Z]$/.test(str(v).toUpperCase());
|
|
228
|
+
export const isGSTIN = (v) => {
|
|
229
|
+
const s = str(v).toUpperCase();
|
|
230
|
+
return (
|
|
231
|
+
/^\d{2}[A-Z]{5}\d{4}[A-Z]\dZ[A-Z0-9]$/.test(s) && isPAN(s.slice(2, 12))
|
|
232
|
+
);
|
|
233
|
+
};
|
|
234
|
+
export const isIFSC = (v) =>
|
|
235
|
+
/^[A-Z]{4}0[A-Z0-9]{6}$/.test(str(v).toUpperCase());
|
|
236
|
+
export const isUPI = (v) => /^[\w.-]{2,256}@[A-Za-z]{2,64}$/.test(str(v));
|
|
237
|
+
export const isIndianVehicleNumber = (v) =>
|
|
238
|
+
/^[A-Z]{2}\d{1,2}[A-Z]{1,3}\d{4}$/.test(
|
|
239
|
+
str(v).replace(/\s/g, "").toUpperCase(),
|
|
240
|
+
);
|
|
241
|
+
export const isBankAccount = (v, o = {}) => {
|
|
242
|
+
const s = str(v).replace(/\s/g, "");
|
|
243
|
+
return (
|
|
244
|
+
/^\d+$/.test(s) &&
|
|
245
|
+
s.length >= (o.minLength ?? 9) &&
|
|
246
|
+
s.length <= (o.maxLength ?? 18)
|
|
247
|
+
);
|
|
248
|
+
};
|
|
249
|
+
export const isConfirmPassword = (a, b) =>
|
|
250
|
+
typeof a === "string" && typeof b === "string" && a === b;
|
|
251
|
+
export const isFileValid = (file, o = {}) =>
|
|
252
|
+
!!file &&
|
|
253
|
+
typeof file === "object" &&
|
|
254
|
+
typeof file.size === "number" &&
|
|
255
|
+
file.size >= 0 &&
|
|
256
|
+
file.size <= (o.maxSize ?? Infinity) &&
|
|
257
|
+
(!o.types?.length || o.types.includes(file.type)) &&
|
|
258
|
+
(!o.extensions?.length ||
|
|
259
|
+
o.extensions.some((x) =>
|
|
260
|
+
String(file.name || "")
|
|
261
|
+
.toLowerCase()
|
|
262
|
+
.endsWith(x.toLowerCase()),
|
|
263
|
+
));
|
|
264
|
+
export const isArrayOf = (v, fn) =>
|
|
265
|
+
Array.isArray(v) && typeof fn === "function" && v.every(fn);
|
|
266
|
+
export const addValidator = (name, fn) => {
|
|
267
|
+
if (!/^[A-Za-z][\w]*$/.test(name) || typeof fn !== "function")
|
|
268
|
+
throw new TypeError("Use a valid validator name and function.");
|
|
269
|
+
custom[name] = fn;
|
|
270
|
+
};
|
|
271
|
+
export const getCustomValidator = (name) => custom[name];
|
|
272
|
+
|
|
273
|
+
const rules = {
|
|
274
|
+
required: isPresent,
|
|
275
|
+
email: isEmail,
|
|
276
|
+
phone: isPhone,
|
|
277
|
+
indianPhone: (v) => isIndianPhone(v, { allowWithoutCountryCode: true }),
|
|
278
|
+
pinCode: isIndianPinCode,
|
|
279
|
+
postalCode: isPostalCode,
|
|
280
|
+
password: isStrongPassword,
|
|
281
|
+
url: isURL,
|
|
282
|
+
domain: isDomain,
|
|
283
|
+
uuid: isUUID,
|
|
284
|
+
ipv4: isIPv4,
|
|
285
|
+
ipv6: isIPv6,
|
|
286
|
+
ip: isIP,
|
|
287
|
+
creditCard: isCreditCard,
|
|
288
|
+
date: isDate,
|
|
289
|
+
dateTime: isDateTime,
|
|
290
|
+
username: isUsername,
|
|
291
|
+
slug: isSlug,
|
|
292
|
+
hexColor: isHexColor,
|
|
293
|
+
alphanumeric: isAlphanumeric,
|
|
294
|
+
numeric: isNumeric,
|
|
295
|
+
integer: isInteger,
|
|
296
|
+
json: isJSON,
|
|
297
|
+
pan: isPAN,
|
|
298
|
+
gstin: isGSTIN,
|
|
299
|
+
ifsc: isIFSC,
|
|
300
|
+
upi: isUPI,
|
|
301
|
+
vehicleNumber: isIndianVehicleNumber,
|
|
302
|
+
bankAccount: isBankAccount,
|
|
303
|
+
};
|
|
304
|
+
const messages = {
|
|
305
|
+
required: "This field is required.",
|
|
306
|
+
email: "Please enter a valid email address.",
|
|
307
|
+
phone: "Please enter a valid phone number.",
|
|
308
|
+
indianPhone: "Please enter a valid Indian mobile number.",
|
|
309
|
+
pinCode: "Please enter a valid Indian PIN code.",
|
|
310
|
+
postalCode: "Please enter a valid postal code.",
|
|
311
|
+
password: "Password does not meet the requirements.",
|
|
312
|
+
url: "Please enter a valid URL.",
|
|
313
|
+
domain: "Please enter a valid domain.",
|
|
314
|
+
uuid: "Please enter a valid UUID.",
|
|
315
|
+
ipv4: "Please enter a valid IPv4 address.",
|
|
316
|
+
ipv6: "Please enter a valid IPv6 address.",
|
|
317
|
+
ip: "Please enter a valid IP address.",
|
|
318
|
+
creditCard: "Please enter a valid card number.",
|
|
319
|
+
date: "Enter a valid date (YYYY-MM-DD).",
|
|
320
|
+
dateTime: "Enter a valid date and time.",
|
|
321
|
+
username: "Username format is invalid.",
|
|
322
|
+
slug: "Slug format is invalid.",
|
|
323
|
+
hexColor: "Enter a valid hex colour.",
|
|
324
|
+
alphanumeric: "Only letters and numbers are allowed.",
|
|
325
|
+
numeric: "Enter a valid number.",
|
|
326
|
+
integer: "Enter a whole number.",
|
|
327
|
+
json: "Enter valid JSON.",
|
|
328
|
+
pan: "Enter a valid PAN format.",
|
|
329
|
+
gstin: "Enter a valid GSTIN format.",
|
|
330
|
+
ifsc: "Enter a valid IFSC code.",
|
|
331
|
+
upi: "Enter a valid UPI ID.",
|
|
332
|
+
vehicleNumber: "Enter a valid vehicle registration number.",
|
|
333
|
+
bankAccount: "Enter a valid bank account number.",
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
/** Validate one value. Rules may be strings, arrays, rule objects, or functions. */
|
|
337
|
+
export const validate = (value, ruleList, options = {}) => {
|
|
338
|
+
const errors = [];
|
|
339
|
+
const list = Array.isArray(ruleList) ? ruleList : [ruleList];
|
|
340
|
+
for (const rule of list) {
|
|
341
|
+
let name,
|
|
342
|
+
opts = {},
|
|
343
|
+
msg;
|
|
344
|
+
if (typeof rule === "string") name = rule;
|
|
345
|
+
else if (typeof rule === "function") {
|
|
346
|
+
if (!rule(value)) errors.push(options.message || "Value is invalid.");
|
|
347
|
+
continue;
|
|
348
|
+
} else if (plain(rule)) {
|
|
349
|
+
name = rule.name || rule.rule;
|
|
350
|
+
opts = rule;
|
|
351
|
+
msg = rule.message;
|
|
352
|
+
} else continue;
|
|
353
|
+
if (name === "minLength") {
|
|
354
|
+
const n = opts.value ?? opts.min;
|
|
355
|
+
if (!hasMinLength(value, n))
|
|
356
|
+
errors.push(msg || `Must be at least ${n} characters.`);
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
if (name === "maxLength") {
|
|
360
|
+
const n = opts.value ?? opts.max;
|
|
361
|
+
if (!hasMaxLength(value, n))
|
|
362
|
+
errors.push(msg || `Must be no more than ${n} characters.`);
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
if (name === "min") {
|
|
366
|
+
const n = opts.value ?? opts.min;
|
|
367
|
+
if (typeof value !== "number" || value < n)
|
|
368
|
+
errors.push(msg || `Must be at least ${n}.`);
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (name === "max") {
|
|
372
|
+
const n = opts.value ?? opts.max;
|
|
373
|
+
if (typeof value !== "number" || value > n)
|
|
374
|
+
errors.push(msg || `Must be no more than ${n}.`);
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
if (name === "oneOf") {
|
|
378
|
+
const choices = opts.values ?? opts.choices;
|
|
379
|
+
if (!isOneOf(value, choices))
|
|
380
|
+
errors.push(msg || "Value is not an allowed option.");
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
if (name === "matches") {
|
|
384
|
+
if (!matchesRegex(value, opts.pattern))
|
|
385
|
+
errors.push(msg || "Value format is invalid.");
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
const fn = rules[name] || custom[name];
|
|
389
|
+
if (!fn) {
|
|
390
|
+
errors.push(`Unknown validation rule: ${name}`);
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
if (!fn(value, opts))
|
|
394
|
+
errors.push(
|
|
395
|
+
msg ||
|
|
396
|
+
options.messages?.[name] ||
|
|
397
|
+
messages[name] ||
|
|
398
|
+
`${name} validation failed.`,
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
return { valid: errors.length === 0, errors };
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
/** Schema: { field: ['required','email'] } or { field: {rules:[...], messages:{...}} } */
|
|
405
|
+
export const validateSchema = (data, schema) => {
|
|
406
|
+
const errors = {};
|
|
407
|
+
if (!plain(data))
|
|
408
|
+
return { valid: false, errors: { _form: ["Expected an object."] } };
|
|
409
|
+
for (const [field, config] of Object.entries(schema || {})) {
|
|
410
|
+
const cfg = Array.isArray(config) ? { rules: config } : config || {};
|
|
411
|
+
const result = validate(data[field], cfg.rules || [], {
|
|
412
|
+
messages: cfg.messages,
|
|
413
|
+
});
|
|
414
|
+
if (!result.valid) errors[field] = result.errors;
|
|
415
|
+
}
|
|
416
|
+
return { valid: Object.keys(errors).length === 0, errors };
|
|
417
|
+
};
|
|
418
|
+
export const validateField = (data, schema, field) => {
|
|
419
|
+
if (!(field in (schema || {})))
|
|
420
|
+
return { valid: false, errors: ["Unknown field."] };
|
|
421
|
+
const cfg = Array.isArray(schema[field])
|
|
422
|
+
? { rules: schema[field] }
|
|
423
|
+
: schema[field] || {};
|
|
424
|
+
return validate(data?.[field], cfg.rules || [], { messages: cfg.messages });
|
|
425
|
+
};
|
|
426
|
+
export const validateArray = (value, itemRules, options = {}) => {
|
|
427
|
+
if (!Array.isArray(value))
|
|
428
|
+
return { valid: false, errors: ["Expected an array."] };
|
|
429
|
+
const errors = [];
|
|
430
|
+
if (options.minItems !== undefined && value.length < options.minItems)
|
|
431
|
+
errors.push(`Must contain at least ${options.minItems} items.`);
|
|
432
|
+
if (options.maxItems !== undefined && value.length > options.maxItems)
|
|
433
|
+
errors.push(`Must contain no more than ${options.maxItems} items.`);
|
|
434
|
+
value.forEach((item, index) => {
|
|
435
|
+
const r = validate(item, itemRules);
|
|
436
|
+
if (!r.valid) errors.push({ index, errors: r.errors });
|
|
437
|
+
});
|
|
438
|
+
return { valid: errors.length === 0, errors };
|
|
439
|
+
};
|
|
440
|
+
export const validateNested = (data, schema) => {
|
|
441
|
+
const errors = {};
|
|
442
|
+
for (const [key, cfg] of Object.entries(schema || {})) {
|
|
443
|
+
const value = data?.[key];
|
|
444
|
+
let r;
|
|
445
|
+
if (cfg?.type === "object") r = validateSchema(value, cfg.schema);
|
|
446
|
+
else if (cfg?.type === "array")
|
|
447
|
+
r = validateArray(value, cfg.rules || [], cfg);
|
|
448
|
+
else r = validate(value, cfg?.rules || cfg || []);
|
|
449
|
+
if (!r.valid) errors[key] = r.errors;
|
|
450
|
+
}
|
|
451
|
+
return { valid: Object.keys(errors).length === 0, errors };
|
|
452
|
+
};
|
|
453
|
+
export const validateObject = (data, validators) => {
|
|
454
|
+
const errors = {};
|
|
455
|
+
if (!plain(data))
|
|
456
|
+
return { valid: false, errors: { _form: "Expected an object." } };
|
|
457
|
+
for (const [k, fn] of Object.entries(validators || {}))
|
|
458
|
+
if (typeof fn === "function" && !fn(data[k])) errors[k] = `Invalid ${k}.`;
|
|
459
|
+
return { valid: Object.keys(errors).length === 0, errors };
|
|
460
|
+
};
|
|
461
|
+
export const quickValidate = {
|
|
462
|
+
isPresent,
|
|
463
|
+
isEmail,
|
|
464
|
+
isIndianPhone,
|
|
465
|
+
isPhone,
|
|
466
|
+
isIndianPinCode,
|
|
467
|
+
isPostalCode,
|
|
468
|
+
isStrongPassword,
|
|
469
|
+
getPasswordStrength,
|
|
470
|
+
isURL,
|
|
471
|
+
isDomain,
|
|
472
|
+
isUUID,
|
|
473
|
+
isIPv4,
|
|
474
|
+
isIPv6,
|
|
475
|
+
isIP,
|
|
476
|
+
isCreditCard,
|
|
477
|
+
isDate,
|
|
478
|
+
isDateTime,
|
|
479
|
+
isUsername,
|
|
480
|
+
isSlug,
|
|
481
|
+
isHexColor,
|
|
482
|
+
isAlphanumeric,
|
|
483
|
+
isNumeric,
|
|
484
|
+
isInteger,
|
|
485
|
+
isJSON,
|
|
486
|
+
hasMinLength,
|
|
487
|
+
hasMaxLength,
|
|
488
|
+
isInRange,
|
|
489
|
+
matchesRegex,
|
|
490
|
+
isOneOf,
|
|
491
|
+
isPAN,
|
|
492
|
+
isGSTIN,
|
|
493
|
+
isIFSC,
|
|
494
|
+
isUPI,
|
|
495
|
+
isIndianVehicleNumber,
|
|
496
|
+
isBankAccount,
|
|
497
|
+
isConfirmPassword,
|
|
498
|
+
isFileValid,
|
|
499
|
+
isArrayOf,
|
|
500
|
+
addValidator,
|
|
501
|
+
getCustomValidator,
|
|
502
|
+
validate,
|
|
503
|
+
validateSchema,
|
|
504
|
+
validateField,
|
|
505
|
+
validateArray,
|
|
506
|
+
validateNested,
|
|
507
|
+
validateObject,
|
|
508
|
+
};
|
|
509
|
+
export default quickValidate;
|