@palakpreet/quick-validate 0.0.0-stage → 2.0.1

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.
Files changed (4) hide show
  1. package/LICENSE +17 -0
  2. package/README.md +309 -2
  3. package/package.json +35 -4
  4. package/src/index.js +1132 -0
package/src/index.js ADDED
@@ -0,0 +1,1132 @@
1
+ /** quick-validate v2 — lightweight JavaScript validators. */
2
+
3
+ const str = (v) => (typeof v === "string" ? v.trim() : "");
4
+
5
+ const numericString = (v) =>
6
+ typeof v === "number" && Number.isFinite(v) ? String(v) : str(v);
7
+
8
+ const plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
9
+
10
+ const custom = Object.create(null);
11
+
12
+ /* -------------------------------------------------------------------------- */
13
+ /* Basic validation */
14
+ /* -------------------------------------------------------------------------- */
15
+
16
+ export const isPresent = (v) =>
17
+ v !== null &&
18
+ v !== undefined &&
19
+ !(typeof v === "string" && !v.trim()) &&
20
+ !(Array.isArray(v) && !v.length);
21
+
22
+ export const isEmail = (v) => {
23
+ const s = str(v);
24
+
25
+ if (!s || s.length > 254 || /\s/.test(s)) return false;
26
+
27
+ const p = s.split("@");
28
+
29
+ if (p.length !== 2) return false;
30
+
31
+ const [local, domain] = p;
32
+ const labels = domain.split(".");
33
+
34
+ return (
35
+ !!local &&
36
+ local.length <= 64 &&
37
+ !local.startsWith(".") &&
38
+ !local.endsWith(".") &&
39
+ !local.includes("..") &&
40
+ /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+$/.test(local) &&
41
+ labels.length >= 2 &&
42
+ labels.every(
43
+ (x) =>
44
+ x.length <= 63 && /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(x),
45
+ ) &&
46
+ /^[A-Za-z]{2,}$/.test(labels.at(-1))
47
+ );
48
+ };
49
+
50
+ /* -------------------------------------------------------------------------- */
51
+ /* Phone numbers */
52
+ /* -------------------------------------------------------------------------- */
53
+
54
+ export const isIndianPhone = (v, o = {}) => {
55
+ let s = str(v).replace(/[\s().-]/g, "");
56
+
57
+ if (!s) return false;
58
+
59
+ const hasCountryCode =
60
+ s.startsWith("+91") ||
61
+ s.startsWith("0091") ||
62
+ (s.length === 12 && s.startsWith("91"));
63
+
64
+ if (s.startsWith("+91")) {
65
+ s = s.slice(3);
66
+ } else if (s.startsWith("0091")) {
67
+ s = s.slice(4);
68
+ } else if (s.length === 12 && s.startsWith("91")) {
69
+ s = s.slice(2);
70
+ }
71
+
72
+ if (o.allowLandline) {
73
+ if (/^0?[1-9]\d{2,4}\d{6,8}$/.test(s)) return true;
74
+ }
75
+
76
+ // Allow 10-digit mobile numbers by default.
77
+ // Set allowWithoutCountryCode: false to require +91 / 0091 / 91.
78
+ if (o.allowWithoutCountryCode === false && !hasCountryCode) {
79
+ return false;
80
+ }
81
+
82
+ return /^[6-9]\d{9}$/.test(s);
83
+ };
84
+
85
+ export const isPhone = (v, country) => {
86
+ const countryCode = String(country ?? "").toUpperCase();
87
+
88
+ if (countryCode === "IN") {
89
+ return isIndianPhone(v, {
90
+ allowWithoutCountryCode: true,
91
+ });
92
+ }
93
+
94
+ const s = str(v).replace(/[\s().-]/g, "");
95
+
96
+ return /^\+?[1-9]\d{7,14}$/.test(s);
97
+ };
98
+
99
+ export const isIndianPinCode = (v) => /^[1-9]\d{5}$/.test(str(v));
100
+
101
+ export const isPostalCode = (v, country) => {
102
+ const s = str(v);
103
+ const c = String(country || "").toUpperCase();
104
+
105
+ if (["IN", "INDIA"].includes(c)) {
106
+ return isIndianPinCode(s);
107
+ }
108
+
109
+ if (["US", "USA"].includes(c)) {
110
+ return /^\d{5}(-\d{4})?$/.test(s);
111
+ }
112
+
113
+ if (["CA", "CANADA"].includes(c)) {
114
+ return /^[A-Z]\d[A-Z][ -]?\d[A-Z]\d$/i.test(s);
115
+ }
116
+
117
+ if (["GB", "UK"].includes(c)) {
118
+ return /^[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$/i.test(s);
119
+ }
120
+
121
+ return /^[A-Z0-9][A-Z0-9 -]{1,10}[A-Z0-9]$/i.test(s);
122
+ };
123
+
124
+ /* -------------------------------------------------------------------------- */
125
+ /* Password validation */
126
+ /* -------------------------------------------------------------------------- */
127
+
128
+ export const isStrongPassword = (v, o = {}) => {
129
+ const s = typeof v === "string" ? v : "";
130
+
131
+ return (
132
+ s.length >= (o.minLength ?? 8) &&
133
+ s.length <= (o.maxLength ?? 128) &&
134
+ (o.lowercase === false || /[a-z]/.test(s)) &&
135
+ (o.uppercase === false || /[A-Z]/.test(s)) &&
136
+ (o.number === false || /\d/.test(s)) &&
137
+ (o.symbol === false || /[^A-Za-z0-9\s]/.test(s)) &&
138
+ (o.noSpaces === false || !/\s/.test(s))
139
+ );
140
+ };
141
+
142
+ export const getPasswordStrength = (v) => {
143
+ const s = typeof v === "string" ? v : "";
144
+
145
+ const checks = {
146
+ length: s.length >= 8,
147
+ lowercase: /[a-z]/.test(s),
148
+ uppercase: /[A-Z]/.test(s),
149
+ number: /\d/.test(s),
150
+ symbol: /[^A-Za-z0-9\s]/.test(s),
151
+ noSpaces: !/\s/.test(s),
152
+ };
153
+
154
+ let score = Object.values(checks).filter(Boolean).length;
155
+
156
+ if (s.length >= 14) score++;
157
+
158
+ if (s.length < 8) {
159
+ score = Math.min(score, 1);
160
+ }
161
+
162
+ score = Math.min(4, score);
163
+
164
+ return {
165
+ score,
166
+ label: ["very-weak", "weak", "fair", "strong", "very-strong"][score],
167
+ checks,
168
+ };
169
+ };
170
+
171
+ /* -------------------------------------------------------------------------- */
172
+ /* URLs and domains */
173
+ /* -------------------------------------------------------------------------- */
174
+
175
+ export const isURL = (v, o = {}) => {
176
+ const s = str(v);
177
+
178
+ if (!s || /\s/.test(s)) return false;
179
+
180
+ try {
181
+ const u = new URL(/^[a-z][a-z\d+.-]*:/i.test(s) ? s : `https://${s}`);
182
+
183
+ return (
184
+ ["http:", "https:"].includes(u.protocol) &&
185
+ (!o.requireHttps || u.protocol === "https:") &&
186
+ !!u.hostname &&
187
+ (o.allowLocalhost ||
188
+ !(u.hostname === "localhost" || !u.hostname.includes(".")))
189
+ );
190
+ } catch {
191
+ return false;
192
+ }
193
+ };
194
+
195
+ export const isDomain = (v) => {
196
+ const s = str(v).toLowerCase();
197
+
198
+ if (
199
+ !s ||
200
+ s.length > 253 ||
201
+ s.includes("/") ||
202
+ s.includes("://") ||
203
+ s.includes("@") ||
204
+ s.includes(":")
205
+ ) {
206
+ return false;
207
+ }
208
+
209
+ const labels = s.split(".");
210
+
211
+ if (labels.length < 2) return false;
212
+
213
+ if (
214
+ !labels.every(
215
+ (label) =>
216
+ label.length >= 1 &&
217
+ label.length <= 63 &&
218
+ /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label),
219
+ )
220
+ ) {
221
+ return false;
222
+ }
223
+
224
+ return /^[a-z]{2,}$/.test(labels.at(-1));
225
+ };
226
+
227
+ /* -------------------------------------------------------------------------- */
228
+ /* UUID and IP addresses */
229
+ /* -------------------------------------------------------------------------- */
230
+
231
+ export const isUUID = (v) =>
232
+ /^[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(
233
+ str(v),
234
+ );
235
+
236
+ export const isIPv4 = (v) => {
237
+ const p = str(v).split(".");
238
+
239
+ return (
240
+ p.length === 4 &&
241
+ p.every(
242
+ (x) =>
243
+ /^\d{1,3}$/.test(x) &&
244
+ Number(x) <= 255 &&
245
+ (x === "0" || !x.startsWith("0")),
246
+ )
247
+ );
248
+ };
249
+
250
+ export const isIPv6 = (v) => {
251
+ const s = str(v);
252
+
253
+ if (!s.includes(":") || !/^[\da-f:]+$/i.test(s)) {
254
+ return false;
255
+ }
256
+
257
+ try {
258
+ new URL(`http://[${s}]/`);
259
+ return true;
260
+ } catch {
261
+ return false;
262
+ }
263
+ };
264
+
265
+ export const isIP = (v) => isIPv4(v) || isIPv6(v);
266
+
267
+ /* -------------------------------------------------------------------------- */
268
+ /* Credit cards */
269
+ /* -------------------------------------------------------------------------- */
270
+
271
+ export const isCreditCard = (v) => {
272
+ const d = str(v).replace(/[\s-]/g, "");
273
+
274
+ if (!/^\d{13,19}$/.test(d)) return false;
275
+
276
+ let sum = 0;
277
+ let twice = false;
278
+
279
+ for (let i = d.length - 1; i >= 0; i--) {
280
+ let n = Number(d[i]);
281
+
282
+ if (twice) {
283
+ n *= 2;
284
+
285
+ if (n > 9) n -= 9;
286
+ }
287
+
288
+ sum += n;
289
+ twice = !twice;
290
+ }
291
+
292
+ return sum % 10 === 0;
293
+ };
294
+
295
+ /* -------------------------------------------------------------------------- */
296
+ /* Date validation */
297
+ /* -------------------------------------------------------------------------- */
298
+
299
+ export const isDate = (v) => {
300
+ const s = str(v);
301
+
302
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) {
303
+ return false;
304
+ }
305
+
306
+ const [year, month, day] = s.split("-").map(Number);
307
+
308
+ if (year < 1 || year > 9999) return false;
309
+
310
+ const daysInMonth = [
311
+ 31,
312
+ year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28,
313
+ 31,
314
+ 30,
315
+ 31,
316
+ 30,
317
+ 31,
318
+ 31,
319
+ 30,
320
+ 31,
321
+ 30,
322
+ 31,
323
+ ];
324
+
325
+ return month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth[month - 1];
326
+ };
327
+
328
+ export const isDateTime = (v) => {
329
+ const s = str(v);
330
+
331
+ const pattern =
332
+ /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:\d{2})?$/;
333
+
334
+ const match = s.match(pattern);
335
+
336
+ if (!match) return false;
337
+
338
+ const [, date, hours, minutes, seconds = "0", , timezone] = match;
339
+
340
+ if (!isDate(date)) return false;
341
+
342
+ if (Number(hours) > 23) return false;
343
+ if (Number(minutes) > 59) return false;
344
+ if (Number(seconds) > 59) return false;
345
+
346
+ if (timezone && timezone !== "Z") {
347
+ const [, offsetHours, offsetMinutes] = timezone.match(
348
+ /^[+-](\d{2}):(\d{2})$/,
349
+ );
350
+
351
+ if (Number(offsetHours) > 14) return false;
352
+ if (Number(offsetMinutes) > 59) return false;
353
+
354
+ if (Number(offsetHours) === 14 && Number(offsetMinutes) !== 0) {
355
+ return false;
356
+ }
357
+ }
358
+
359
+ return !Number.isNaN(Date.parse(s));
360
+ };
361
+
362
+ /* -------------------------------------------------------------------------- */
363
+ /* Usernames and text formats */
364
+ /* -------------------------------------------------------------------------- */
365
+
366
+ export const isUsername = (v, o = {}) => {
367
+ const s = str(v);
368
+
369
+ return (
370
+ s.length >= (o.minLength ?? 3) &&
371
+ s.length <= (o.maxLength ?? 20) &&
372
+ /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(s)
373
+ );
374
+ };
375
+
376
+ export const isSlug = (v) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(str(v));
377
+
378
+ export const isHexColor = (v, alpha = false) => {
379
+ const pattern = alpha
380
+ ? /^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i
381
+ : /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
382
+
383
+ return pattern.test(str(v));
384
+ };
385
+
386
+ export const isAlphanumeric = (v) => /^[A-Za-z0-9]+$/.test(str(v));
387
+
388
+ /* -------------------------------------------------------------------------- */
389
+ /* Numeric validation */
390
+ /* -------------------------------------------------------------------------- */
391
+
392
+ export const isNumeric = (v, o = {}) => {
393
+ const s = numericString(v);
394
+
395
+ if (!s) return false;
396
+
397
+ const sign = o.negative ? "-?" : "";
398
+ const decimal = o.decimal === false ? "" : "(?:\\.\\d+)?";
399
+
400
+ return new RegExp(`^${sign}\\d+${decimal}$`).test(s);
401
+ };
402
+
403
+ export const isInteger = (v, o = {}) => {
404
+ const s = numericString(v);
405
+
406
+ if (!s) return false;
407
+
408
+ const pattern = o.negative === false ? /^\d+$/ : /^-?\d+$/;
409
+
410
+ if (!pattern.test(s)) return false;
411
+
412
+ const n = Number(s);
413
+
414
+ return (
415
+ Number.isSafeInteger(n) &&
416
+ (o.min === undefined || n >= o.min) &&
417
+ (o.max === undefined || n <= o.max)
418
+ );
419
+ };
420
+
421
+ /* -------------------------------------------------------------------------- */
422
+ /* JSON and length validation */
423
+ /* -------------------------------------------------------------------------- */
424
+
425
+ export const isJSON = (v) => {
426
+ if (typeof v !== "string") return false;
427
+
428
+ try {
429
+ JSON.parse(v);
430
+ return true;
431
+ } catch {
432
+ return false;
433
+ }
434
+ };
435
+
436
+ export const hasMinLength = (v, n) => typeof v === "string" && v.length >= n;
437
+
438
+ export const hasMaxLength = (v, n) => typeof v === "string" && v.length <= n;
439
+
440
+ /* -------------------------------------------------------------------------- */
441
+ /* Range, regex and option validation */
442
+ /* -------------------------------------------------------------------------- */
443
+
444
+ export const isInRange = (v, min, max) =>
445
+ typeof v === "number" && Number.isFinite(v) && v >= min && v <= max;
446
+
447
+ export const matchesRegex = (v, r) => {
448
+ if (typeof v !== "string" || !(r instanceof RegExp)) {
449
+ return false;
450
+ }
451
+
452
+ r.lastIndex = 0;
453
+
454
+ const result = r.test(v);
455
+
456
+ r.lastIndex = 0;
457
+
458
+ return result;
459
+ };
460
+
461
+ export const isOneOf = (v, values) =>
462
+ Array.isArray(values) && values.includes(v);
463
+
464
+ /* -------------------------------------------------------------------------- */
465
+ /* Indian business identifiers */
466
+ /* -------------------------------------------------------------------------- */
467
+
468
+ export const isPAN = (v) => /^[A-Z]{5}\d{4}[A-Z]$/.test(str(v).toUpperCase());
469
+
470
+ export const isGSTIN = (v) => {
471
+ const s = str(v).toUpperCase();
472
+
473
+ return (
474
+ /^\d{2}[A-Z]{5}\d{4}[A-Z]\dZ[A-Z0-9]$/.test(s) && isPAN(s.slice(2, 12))
475
+ );
476
+ };
477
+
478
+ export const isIFSC = (v) =>
479
+ /^[A-Z]{4}0[A-Z0-9]{6}$/.test(str(v).toUpperCase());
480
+
481
+ export const isUPI = (v) => /^[\w.-]{2,256}@[A-Za-z]{2,64}$/.test(str(v));
482
+
483
+ export const isIndianVehicleNumber = (v) =>
484
+ /^[A-Z]{2}\d{1,2}[A-Z]{1,3}\d{4}$/.test(
485
+ str(v).replace(/\s/g, "").toUpperCase(),
486
+ );
487
+
488
+ export const isBankAccount = (v, o = {}) => {
489
+ const s = str(v).replace(/\s/g, "");
490
+
491
+ return (
492
+ /^\d+$/.test(s) &&
493
+ s.length >= (o.minLength ?? 9) &&
494
+ s.length <= (o.maxLength ?? 18)
495
+ );
496
+ };
497
+
498
+ /* -------------------------------------------------------------------------- */
499
+ /* Password confirmation */
500
+ /* -------------------------------------------------------------------------- */
501
+
502
+ export const isConfirmPassword = (a, b) =>
503
+ typeof a === "string" && typeof b === "string" && a === b;
504
+
505
+ /* -------------------------------------------------------------------------- */
506
+ /* File validation */
507
+ /* -------------------------------------------------------------------------- */
508
+
509
+ export const isFileValid = (file, o = {}) =>
510
+ !!file &&
511
+ typeof file === "object" &&
512
+ typeof file.size === "number" &&
513
+ file.size >= 0 &&
514
+ file.size <= (o.maxSize ?? Infinity) &&
515
+ (!o.types?.length || o.types.includes(file.type)) &&
516
+ (!o.extensions?.length ||
517
+ o.extensions.some((x) =>
518
+ String(file.name || "")
519
+ .toLowerCase()
520
+ .endsWith(String(x).toLowerCase()),
521
+ ));
522
+
523
+ /* -------------------------------------------------------------------------- */
524
+ /* Array validation */
525
+ /* -------------------------------------------------------------------------- */
526
+
527
+ export const isArrayOf = (v, fn) =>
528
+ Array.isArray(v) && typeof fn === "function" && v.every(fn);
529
+
530
+ /* -------------------------------------------------------------------------- */
531
+ /* Custom validators */
532
+ /* -------------------------------------------------------------------------- */
533
+
534
+ export const addValidator = (name, fn) => {
535
+ if (
536
+ typeof name !== "string" ||
537
+ !/^[A-Za-z][\w]*$/.test(name) ||
538
+ typeof fn !== "function"
539
+ ) {
540
+ throw new TypeError("Use a valid validator name and function.");
541
+ }
542
+
543
+ custom[name] = fn;
544
+ };
545
+
546
+ export const getCustomValidator = (name) =>
547
+ typeof name === "string" && Object.hasOwn(custom, name)
548
+ ? custom[name]
549
+ : undefined;
550
+
551
+ /* -------------------------------------------------------------------------- */
552
+ /* Built-in validation rules */
553
+ /* -------------------------------------------------------------------------- */
554
+
555
+ const rules = {
556
+ required: isPresent,
557
+ email: isEmail,
558
+ phone: isPhone,
559
+ indianPhone: (v) =>
560
+ isIndianPhone(v, {
561
+ allowWithoutCountryCode: true,
562
+ }),
563
+ pinCode: isIndianPinCode,
564
+ postalCode: isPostalCode,
565
+ password: isStrongPassword,
566
+ url: isURL,
567
+ domain: isDomain,
568
+ uuid: isUUID,
569
+ ipv4: isIPv4,
570
+ ipv6: isIPv6,
571
+ ip: isIP,
572
+ creditCard: isCreditCard,
573
+ date: isDate,
574
+ dateTime: isDateTime,
575
+ username: isUsername,
576
+ slug: isSlug,
577
+ hexColor: isHexColor,
578
+ alphanumeric: isAlphanumeric,
579
+ numeric: isNumeric,
580
+ integer: isInteger,
581
+ json: isJSON,
582
+ pan: isPAN,
583
+ gstin: isGSTIN,
584
+ ifsc: isIFSC,
585
+ upi: isUPI,
586
+ vehicleNumber: isIndianVehicleNumber,
587
+ bankAccount: isBankAccount,
588
+ };
589
+
590
+ /* -------------------------------------------------------------------------- */
591
+ /* Default error messages */
592
+ /* -------------------------------------------------------------------------- */
593
+
594
+ const messages = {
595
+ required: "This field is required.",
596
+ email: "Please enter a valid email address.",
597
+ phone: "Please enter a valid phone number.",
598
+ indianPhone: "Please enter a valid Indian mobile number.",
599
+ pinCode: "Please enter a valid Indian PIN code.",
600
+ postalCode: "Please enter a valid postal code.",
601
+ password: "Password does not meet the requirements.",
602
+ url: "Please enter a valid URL.",
603
+ domain: "Please enter a valid domain.",
604
+ uuid: "Please enter a valid UUID.",
605
+ ipv4: "Please enter a valid IPv4 address.",
606
+ ipv6: "Please enter a valid IPv6 address.",
607
+ ip: "Please enter a valid IP address.",
608
+ creditCard: "Please enter a valid card number.",
609
+ date: "Enter a valid date (YYYY-MM-DD).",
610
+ dateTime: "Enter a valid date and time.",
611
+ username: "Username format is invalid.",
612
+ slug: "Slug format is invalid.",
613
+ hexColor: "Enter a valid hex colour.",
614
+ alphanumeric: "Only letters and numbers are allowed.",
615
+ numeric: "Enter a valid number.",
616
+ integer: "Enter a whole number.",
617
+ json: "Enter valid JSON.",
618
+ pan: "Enter a valid PAN format.",
619
+ gstin: "Enter a valid GSTIN format.",
620
+ ifsc: "Enter a valid IFSC code.",
621
+ upi: "Enter a valid UPI ID.",
622
+ vehicleNumber: "Enter a valid vehicle registration number.",
623
+ bankAccount: "Enter a valid bank account number.",
624
+ };
625
+
626
+ /* -------------------------------------------------------------------------- */
627
+ /* Validate one value */
628
+ /* -------------------------------------------------------------------------- */
629
+
630
+ /**
631
+ * Validate one value.
632
+ *
633
+ * Rules may be:
634
+ * - Strings
635
+ * - Arrays of rules
636
+ * - Rule objects
637
+ * - Custom functions
638
+ */
639
+ export const validate = (value, ruleList, options = {}) => {
640
+ const errors = [];
641
+
642
+ const list = Array.isArray(ruleList) ? ruleList : [ruleList];
643
+
644
+ for (const rule of list) {
645
+ let name;
646
+ let opts = {};
647
+ let msg;
648
+
649
+ if (typeof rule === "string") {
650
+ name = rule;
651
+ } else if (typeof rule === "function") {
652
+ try {
653
+ if (!rule(value)) {
654
+ errors.push(options.message || "Value is invalid.");
655
+ }
656
+ } catch {
657
+ errors.push(options.message || "Value is invalid.");
658
+ }
659
+
660
+ continue;
661
+ } else if (plain(rule)) {
662
+ name = rule.name || rule.rule;
663
+ opts = rule;
664
+ msg = rule.message;
665
+
666
+ if (typeof name !== "string" || !name.trim()) {
667
+ errors.push("Invalid validation rule configuration.");
668
+ continue;
669
+ }
670
+
671
+ if (["min", "max", "minLength", "maxLength"].includes(name)) {
672
+ const n = opts.value ?? opts.min ?? opts.max;
673
+
674
+ if (
675
+ typeof n !== "number" ||
676
+ !Number.isFinite(n) ||
677
+ (["minLength", "maxLength"].includes(name) &&
678
+ (!Number.isInteger(n) || n < 0))
679
+ ) {
680
+ errors.push("Invalid validation rule configuration.");
681
+ continue;
682
+ }
683
+ }
684
+
685
+ if (name === "oneOf") {
686
+ const choices = opts.values ?? opts.choices;
687
+
688
+ if (!Array.isArray(choices)) {
689
+ errors.push("Invalid validation rule configuration.");
690
+ continue;
691
+ }
692
+ }
693
+
694
+ if (name === "matches" && !(opts.pattern instanceof RegExp)) {
695
+ errors.push("Invalid validation rule configuration.");
696
+ continue;
697
+ }
698
+ } else {
699
+ errors.push("Invalid validation rule configuration.");
700
+ continue;
701
+ }
702
+
703
+ if (name === "minLength") {
704
+ const n = opts.value ?? opts.min;
705
+
706
+ if (!hasMinLength(value, n)) {
707
+ errors.push(msg || `Must be at least ${n} characters.`);
708
+ }
709
+
710
+ continue;
711
+ }
712
+
713
+ if (name === "maxLength") {
714
+ const n = opts.value ?? opts.max;
715
+
716
+ if (!hasMaxLength(value, n)) {
717
+ errors.push(msg || `Must be no more than ${n} characters.`);
718
+ }
719
+
720
+ continue;
721
+ }
722
+
723
+ if (name === "min") {
724
+ const n = opts.value ?? opts.min;
725
+
726
+ if (typeof value !== "number" || value < n) {
727
+ errors.push(msg || `Must be at least ${n}.`);
728
+ }
729
+
730
+ continue;
731
+ }
732
+
733
+ if (name === "max") {
734
+ const n = opts.value ?? opts.max;
735
+
736
+ if (typeof value !== "number" || value > n) {
737
+ errors.push(msg || `Must be no more than ${n}.`);
738
+ }
739
+
740
+ continue;
741
+ }
742
+
743
+ if (name === "oneOf") {
744
+ const choices = opts.values ?? opts.choices;
745
+
746
+ if (!isOneOf(value, choices)) {
747
+ errors.push(msg || "Value is not an allowed option.");
748
+ }
749
+
750
+ continue;
751
+ }
752
+
753
+ if (name === "matches") {
754
+ if (!matchesRegex(value, opts.pattern)) {
755
+ errors.push(msg || "Value format is invalid.");
756
+ }
757
+
758
+ continue;
759
+ }
760
+
761
+ const fn = Object.hasOwn(rules, name)
762
+ ? rules[name]
763
+ : getCustomValidator(name);
764
+
765
+ if (typeof fn !== "function") {
766
+ errors.push(`Unknown validation rule: ${name}`);
767
+ continue;
768
+ }
769
+
770
+ try {
771
+ if (!fn(value, opts)) {
772
+ errors.push(
773
+ msg ||
774
+ options.messages?.[name] ||
775
+ messages[name] ||
776
+ `${name} validation failed.`,
777
+ );
778
+ }
779
+ } catch {
780
+ errors.push(msg || `${name} validation failed.`);
781
+ }
782
+ }
783
+
784
+ return {
785
+ valid: errors.length === 0,
786
+ errors,
787
+ };
788
+ };
789
+
790
+ /* -------------------------------------------------------------------------- */
791
+ /* Schema validation */
792
+ /* -------------------------------------------------------------------------- */
793
+
794
+ /**
795
+ * Schema format:
796
+ *
797
+ * {
798
+ * field: ["required", "email"]
799
+ * }
800
+ *
801
+ * Or:
802
+ *
803
+ * {
804
+ * field: {
805
+ * rules: ["required", "email"],
806
+ * messages: {
807
+ * email: "Custom error message"
808
+ * }
809
+ * }
810
+ * }
811
+ */
812
+ export const validateSchema = (data, schema) => {
813
+ const errors = {};
814
+
815
+ if (!plain(data)) {
816
+ return {
817
+ valid: false,
818
+ errors: {
819
+ _form: ["Expected an object."],
820
+ },
821
+ };
822
+ }
823
+
824
+ if (!plain(schema)) {
825
+ return {
826
+ valid: false,
827
+ errors: {
828
+ _schema: ["Expected a schema object."],
829
+ },
830
+ };
831
+ }
832
+
833
+ for (const [field, config] of Object.entries(schema)) {
834
+ let cfg;
835
+
836
+ if (Array.isArray(config)) {
837
+ cfg = { rules: config };
838
+ } else if (plain(config) && Array.isArray(config.rules)) {
839
+ cfg = config;
840
+ } else {
841
+ errors[field] = ["Invalid field validation configuration."];
842
+ continue;
843
+ }
844
+
845
+ const result = validate(data[field], cfg.rules, {
846
+ messages: cfg.messages,
847
+ });
848
+
849
+ if (!result.valid) {
850
+ errors[field] = result.errors;
851
+ }
852
+ }
853
+
854
+ return {
855
+ valid: Object.keys(errors).length === 0,
856
+ errors,
857
+ };
858
+ };
859
+
860
+ /* -------------------------------------------------------------------------- */
861
+ /* Single-field schema validation */
862
+ /* -------------------------------------------------------------------------- */
863
+
864
+ export const validateField = (data, schema, field) => {
865
+ if (!plain(schema) || !Object.hasOwn(schema, field)) {
866
+ return {
867
+ valid: false,
868
+ errors: ["Unknown field."],
869
+ };
870
+ }
871
+
872
+ const config = schema[field];
873
+
874
+ let cfg;
875
+
876
+ if (Array.isArray(config)) {
877
+ cfg = { rules: config };
878
+ } else if (plain(config) && Array.isArray(config.rules)) {
879
+ cfg = config;
880
+ } else {
881
+ return {
882
+ valid: false,
883
+ errors: ["Invalid field validation configuration."],
884
+ };
885
+ }
886
+
887
+ return validate(data?.[field], cfg.rules, {
888
+ messages: cfg.messages,
889
+ });
890
+ };
891
+
892
+ /* -------------------------------------------------------------------------- */
893
+ /* Array schema validation */
894
+ /* -------------------------------------------------------------------------- */
895
+
896
+ export const validateArray = (value, itemRules, options = {}) => {
897
+ if (!Array.isArray(value)) {
898
+ return {
899
+ valid: false,
900
+ errors: ["Expected an array."],
901
+ };
902
+ }
903
+
904
+ if (!plain(options)) {
905
+ return {
906
+ valid: false,
907
+ errors: ["Invalid array validation options."],
908
+ };
909
+ }
910
+
911
+ const errors = [];
912
+
913
+ const validCount = (count) => Number.isInteger(count) && count >= 0;
914
+
915
+ if (options.minItems !== undefined && !validCount(options.minItems)) {
916
+ errors.push("Invalid minItems configuration.");
917
+ }
918
+
919
+ if (options.maxItems !== undefined && !validCount(options.maxItems)) {
920
+ errors.push("Invalid maxItems configuration.");
921
+ }
922
+
923
+ if (
924
+ validCount(options.minItems) &&
925
+ validCount(options.maxItems) &&
926
+ options.minItems > options.maxItems
927
+ ) {
928
+ errors.push("minItems cannot be greater than maxItems.");
929
+ }
930
+
931
+ if (errors.length > 0) {
932
+ return {
933
+ valid: false,
934
+ errors,
935
+ };
936
+ }
937
+
938
+ if (options.minItems !== undefined && value.length < options.minItems) {
939
+ errors.push(`Must contain at least ${options.minItems} items.`);
940
+ }
941
+
942
+ if (options.maxItems !== undefined && value.length > options.maxItems) {
943
+ errors.push(`Must contain no more than ${options.maxItems} items.`);
944
+ }
945
+
946
+ for (let index = 0; index < value.length; index++) {
947
+ const result = validate(value[index], itemRules);
948
+
949
+ if (!result.valid) {
950
+ errors.push({
951
+ index,
952
+ errors: result.errors,
953
+ });
954
+ }
955
+ }
956
+
957
+ return {
958
+ valid: errors.length === 0,
959
+ errors,
960
+ };
961
+ };
962
+
963
+ /* -------------------------------------------------------------------------- */
964
+ /* Nested validation */
965
+ /* -------------------------------------------------------------------------- */
966
+
967
+ /**
968
+ * Nested schema example:
969
+ *
970
+ * {
971
+ * name: ["required"],
972
+ * address: {
973
+ * type: "object",
974
+ * schema: {
975
+ * city: ["required"]
976
+ * }
977
+ * },
978
+ * emails: {
979
+ * type: "array",
980
+ * rules: ["email"],
981
+ * minItems: 1
982
+ * }
983
+ * }
984
+ */
985
+ export const validateNested = (data, schema) => {
986
+ if (!plain(schema)) {
987
+ return {
988
+ valid: false,
989
+ errors: {
990
+ _schema: ["Expected a schema object."],
991
+ },
992
+ };
993
+ }
994
+
995
+ const errors = {};
996
+
997
+ for (const [key, cfg] of Object.entries(schema)) {
998
+ const value = data?.[key];
999
+
1000
+ let result;
1001
+
1002
+ if (plain(cfg) && cfg.type !== undefined) {
1003
+ if (cfg.type === "object") {
1004
+ result = validateSchema(value, cfg.schema);
1005
+ } else if (cfg.type === "array") {
1006
+ result = validateArray(value, cfg.rules ?? [], cfg);
1007
+ } else {
1008
+ errors[key] = ["Invalid validation type."];
1009
+ continue;
1010
+ }
1011
+ } else if (plain(cfg) && Object.hasOwn(cfg, "rules")) {
1012
+ if (!Array.isArray(cfg.rules)) {
1013
+ errors[key] = ["Invalid field validation configuration."];
1014
+ continue;
1015
+ }
1016
+
1017
+ result = validate(value, cfg.rules);
1018
+ } else {
1019
+ result = validate(value, cfg);
1020
+ }
1021
+
1022
+ if (!result.valid) {
1023
+ errors[key] = result.errors;
1024
+ }
1025
+ }
1026
+
1027
+ return {
1028
+ valid: Object.keys(errors).length === 0,
1029
+ errors,
1030
+ };
1031
+ };
1032
+
1033
+ /* -------------------------------------------------------------------------- */
1034
+ /* Object validation */
1035
+ /* -------------------------------------------------------------------------- */
1036
+
1037
+ /**
1038
+ * Validate object fields using validator functions.
1039
+ *
1040
+ * Example:
1041
+ *
1042
+ * validateObject(user, {
1043
+ * email: isEmail,
1044
+ * age: (v) => typeof v === "number" && v >= 18
1045
+ * })
1046
+ */
1047
+ export const validateObject = (data, validators) => {
1048
+ const errors = {};
1049
+
1050
+ if (!plain(data)) {
1051
+ return {
1052
+ valid: false,
1053
+ errors: {
1054
+ _form: "Expected an object.",
1055
+ },
1056
+ };
1057
+ }
1058
+
1059
+ for (const [key, fn] of Object.entries(validators || {})) {
1060
+ if (typeof fn !== "function") {
1061
+ continue;
1062
+ }
1063
+
1064
+ try {
1065
+ if (!fn(data[key])) {
1066
+ errors[key] = `Invalid ${key}.`;
1067
+ }
1068
+ } catch {
1069
+ errors[key] = `Invalid ${key}.`;
1070
+ }
1071
+ }
1072
+
1073
+ return {
1074
+ valid: Object.keys(errors).length === 0,
1075
+ errors,
1076
+ };
1077
+ };
1078
+
1079
+ /* -------------------------------------------------------------------------- */
1080
+ /* Main exported object */
1081
+ /* -------------------------------------------------------------------------- */
1082
+
1083
+ export const quickValidate = {
1084
+ isPresent,
1085
+ isEmail,
1086
+ isIndianPhone,
1087
+ isPhone,
1088
+ isIndianPinCode,
1089
+ isPostalCode,
1090
+ isStrongPassword,
1091
+ getPasswordStrength,
1092
+ isURL,
1093
+ isDomain,
1094
+ isUUID,
1095
+ isIPv4,
1096
+ isIPv6,
1097
+ isIP,
1098
+ isCreditCard,
1099
+ isDate,
1100
+ isDateTime,
1101
+ isUsername,
1102
+ isSlug,
1103
+ isHexColor,
1104
+ isAlphanumeric,
1105
+ isNumeric,
1106
+ isInteger,
1107
+ isJSON,
1108
+ hasMinLength,
1109
+ hasMaxLength,
1110
+ isInRange,
1111
+ matchesRegex,
1112
+ isOneOf,
1113
+ isPAN,
1114
+ isGSTIN,
1115
+ isIFSC,
1116
+ isUPI,
1117
+ isIndianVehicleNumber,
1118
+ isBankAccount,
1119
+ isConfirmPassword,
1120
+ isFileValid,
1121
+ isArrayOf,
1122
+ addValidator,
1123
+ getCustomValidator,
1124
+ validate,
1125
+ validateSchema,
1126
+ validateField,
1127
+ validateArray,
1128
+ validateNested,
1129
+ validateObject,
1130
+ };
1131
+
1132
+ export default quickValidate;