dino-validation 0.3.0 → 0.4.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.
Files changed (208) hide show
  1. package/README.md +84 -1677
  2. package/dist/dv.esm.js +92 -30
  3. package/dist/dv.esm.js.map +1 -1
  4. package/dist/dv.js +92 -30
  5. package/dist/dv.js.map +1 -1
  6. package/dist/dv.min.js +2 -2
  7. package/dist/dv.min.js.map +1 -1
  8. package/dist/localization/messages_ar.esm.js +1 -1
  9. package/dist/localization/messages_ar.js +1 -1
  10. package/dist/localization/messages_ar.min.js +1 -1
  11. package/dist/localization/messages_az.esm.js +1 -1
  12. package/dist/localization/messages_az.js +1 -1
  13. package/dist/localization/messages_az.min.js +1 -1
  14. package/dist/localization/messages_bg.esm.js +1 -1
  15. package/dist/localization/messages_bg.js +1 -1
  16. package/dist/localization/messages_bg.min.js +1 -1
  17. package/dist/localization/messages_bn_BD.esm.js +1 -1
  18. package/dist/localization/messages_bn_BD.js +1 -1
  19. package/dist/localization/messages_bn_BD.min.js +1 -1
  20. package/dist/localization/messages_ca.esm.js +1 -1
  21. package/dist/localization/messages_ca.js +1 -1
  22. package/dist/localization/messages_ca.min.js +1 -1
  23. package/dist/localization/messages_cs.esm.js +1 -1
  24. package/dist/localization/messages_cs.js +1 -1
  25. package/dist/localization/messages_cs.min.js +1 -1
  26. package/dist/localization/messages_da.esm.js +1 -1
  27. package/dist/localization/messages_da.js +1 -1
  28. package/dist/localization/messages_da.min.js +1 -1
  29. package/dist/localization/messages_de.esm.js +1 -1
  30. package/dist/localization/messages_de.js +1 -1
  31. package/dist/localization/messages_de.min.js +1 -1
  32. package/dist/localization/messages_el.esm.js +1 -1
  33. package/dist/localization/messages_el.js +1 -1
  34. package/dist/localization/messages_el.min.js +1 -1
  35. package/dist/localization/messages_es.esm.js +1 -1
  36. package/dist/localization/messages_es.js +1 -1
  37. package/dist/localization/messages_es.min.js +1 -1
  38. package/dist/localization/messages_es_AR.esm.js +1 -1
  39. package/dist/localization/messages_es_AR.js +1 -1
  40. package/dist/localization/messages_es_AR.min.js +1 -1
  41. package/dist/localization/messages_es_PE.esm.js +1 -1
  42. package/dist/localization/messages_es_PE.js +1 -1
  43. package/dist/localization/messages_es_PE.min.js +1 -1
  44. package/dist/localization/messages_et.esm.js +1 -1
  45. package/dist/localization/messages_et.js +1 -1
  46. package/dist/localization/messages_et.min.js +1 -1
  47. package/dist/localization/messages_eu.esm.js +1 -1
  48. package/dist/localization/messages_eu.js +1 -1
  49. package/dist/localization/messages_eu.min.js +1 -1
  50. package/dist/localization/messages_fa.esm.js +1 -1
  51. package/dist/localization/messages_fa.js +1 -1
  52. package/dist/localization/messages_fa.min.js +1 -1
  53. package/dist/localization/messages_fi.esm.js +1 -1
  54. package/dist/localization/messages_fi.js +1 -1
  55. package/dist/localization/messages_fi.min.js +1 -1
  56. package/dist/localization/messages_fr.esm.js +1 -1
  57. package/dist/localization/messages_fr.js +1 -1
  58. package/dist/localization/messages_fr.min.js +1 -1
  59. package/dist/localization/messages_ge.esm.js +1 -1
  60. package/dist/localization/messages_ge.js +1 -1
  61. package/dist/localization/messages_ge.min.js +1 -1
  62. package/dist/localization/messages_gl.esm.js +1 -1
  63. package/dist/localization/messages_gl.js +1 -1
  64. package/dist/localization/messages_gl.min.js +1 -1
  65. package/dist/localization/messages_he.esm.js +1 -1
  66. package/dist/localization/messages_he.js +1 -1
  67. package/dist/localization/messages_he.min.js +1 -1
  68. package/dist/localization/messages_hi.esm.js +1 -1
  69. package/dist/localization/messages_hi.js +1 -1
  70. package/dist/localization/messages_hi.min.js +1 -1
  71. package/dist/localization/messages_hr.esm.js +1 -1
  72. package/dist/localization/messages_hr.js +1 -1
  73. package/dist/localization/messages_hr.min.js +1 -1
  74. package/dist/localization/messages_hu.esm.js +1 -1
  75. package/dist/localization/messages_hu.js +1 -1
  76. package/dist/localization/messages_hu.min.js +1 -1
  77. package/dist/localization/messages_hy_AM.esm.js +1 -1
  78. package/dist/localization/messages_hy_AM.js +1 -1
  79. package/dist/localization/messages_hy_AM.min.js +1 -1
  80. package/dist/localization/messages_id.esm.js +1 -1
  81. package/dist/localization/messages_id.js +1 -1
  82. package/dist/localization/messages_id.min.js +1 -1
  83. package/dist/localization/messages_is.esm.js +1 -1
  84. package/dist/localization/messages_is.js +1 -1
  85. package/dist/localization/messages_is.min.js +1 -1
  86. package/dist/localization/messages_it.esm.js +1 -1
  87. package/dist/localization/messages_it.js +1 -1
  88. package/dist/localization/messages_it.min.js +1 -1
  89. package/dist/localization/messages_ja.esm.js +1 -1
  90. package/dist/localization/messages_ja.js +1 -1
  91. package/dist/localization/messages_ja.min.js +1 -1
  92. package/dist/localization/messages_ka.esm.js +1 -1
  93. package/dist/localization/messages_ka.js +1 -1
  94. package/dist/localization/messages_ka.min.js +1 -1
  95. package/dist/localization/messages_kk.esm.js +1 -1
  96. package/dist/localization/messages_kk.js +1 -1
  97. package/dist/localization/messages_kk.min.js +1 -1
  98. package/dist/localization/messages_ko.esm.js +1 -1
  99. package/dist/localization/messages_ko.js +1 -1
  100. package/dist/localization/messages_ko.min.js +1 -1
  101. package/dist/localization/messages_lt.esm.js +1 -1
  102. package/dist/localization/messages_lt.js +1 -1
  103. package/dist/localization/messages_lt.min.js +1 -1
  104. package/dist/localization/messages_lv.esm.js +1 -1
  105. package/dist/localization/messages_lv.js +1 -1
  106. package/dist/localization/messages_lv.min.js +1 -1
  107. package/dist/localization/messages_mk.esm.js +1 -1
  108. package/dist/localization/messages_mk.js +1 -1
  109. package/dist/localization/messages_mk.min.js +1 -1
  110. package/dist/localization/messages_my.esm.js +1 -1
  111. package/dist/localization/messages_my.js +1 -1
  112. package/dist/localization/messages_my.min.js +1 -1
  113. package/dist/localization/messages_nl.esm.js +1 -1
  114. package/dist/localization/messages_nl.js +1 -1
  115. package/dist/localization/messages_nl.min.js +1 -1
  116. package/dist/localization/messages_no.esm.js +1 -1
  117. package/dist/localization/messages_no.js +1 -1
  118. package/dist/localization/messages_no.min.js +1 -1
  119. package/dist/localization/messages_pl.esm.js +1 -1
  120. package/dist/localization/messages_pl.js +1 -1
  121. package/dist/localization/messages_pl.min.js +1 -1
  122. package/dist/localization/messages_pt_BR.esm.js +1 -1
  123. package/dist/localization/messages_pt_BR.js +1 -1
  124. package/dist/localization/messages_pt_BR.min.js +1 -1
  125. package/dist/localization/messages_pt_PT.esm.js +1 -1
  126. package/dist/localization/messages_pt_PT.js +1 -1
  127. package/dist/localization/messages_pt_PT.min.js +1 -1
  128. package/dist/localization/messages_ro.esm.js +1 -1
  129. package/dist/localization/messages_ro.js +1 -1
  130. package/dist/localization/messages_ro.min.js +1 -1
  131. package/dist/localization/messages_ru.esm.js +1 -1
  132. package/dist/localization/messages_ru.js +1 -1
  133. package/dist/localization/messages_ru.min.js +1 -1
  134. package/dist/localization/messages_sd.esm.js +1 -1
  135. package/dist/localization/messages_sd.js +1 -1
  136. package/dist/localization/messages_sd.min.js +1 -1
  137. package/dist/localization/messages_si.esm.js +1 -1
  138. package/dist/localization/messages_si.js +1 -1
  139. package/dist/localization/messages_si.min.js +1 -1
  140. package/dist/localization/messages_sk.esm.js +1 -1
  141. package/dist/localization/messages_sk.js +1 -1
  142. package/dist/localization/messages_sk.min.js +1 -1
  143. package/dist/localization/messages_sl.esm.js +1 -1
  144. package/dist/localization/messages_sl.js +1 -1
  145. package/dist/localization/messages_sl.min.js +1 -1
  146. package/dist/localization/messages_sr.esm.js +1 -1
  147. package/dist/localization/messages_sr.js +1 -1
  148. package/dist/localization/messages_sr.min.js +1 -1
  149. package/dist/localization/messages_sr_lat.esm.js +1 -1
  150. package/dist/localization/messages_sr_lat.js +1 -1
  151. package/dist/localization/messages_sr_lat.min.js +1 -1
  152. package/dist/localization/messages_sv.esm.js +1 -1
  153. package/dist/localization/messages_sv.js +1 -1
  154. package/dist/localization/messages_sv.min.js +1 -1
  155. package/dist/localization/messages_th.esm.js +1 -1
  156. package/dist/localization/messages_th.js +1 -1
  157. package/dist/localization/messages_th.min.js +1 -1
  158. package/dist/localization/messages_tj.esm.js +1 -1
  159. package/dist/localization/messages_tj.js +1 -1
  160. package/dist/localization/messages_tj.min.js +1 -1
  161. package/dist/localization/messages_tr.esm.js +1 -1
  162. package/dist/localization/messages_tr.js +1 -1
  163. package/dist/localization/messages_tr.min.js +1 -1
  164. package/dist/localization/messages_uk.esm.js +1 -1
  165. package/dist/localization/messages_uk.js +1 -1
  166. package/dist/localization/messages_uk.min.js +1 -1
  167. package/dist/localization/messages_ur.esm.js +1 -1
  168. package/dist/localization/messages_ur.js +1 -1
  169. package/dist/localization/messages_ur.min.js +1 -1
  170. package/dist/localization/messages_vi.esm.js +1 -1
  171. package/dist/localization/messages_vi.js +1 -1
  172. package/dist/localization/messages_vi.min.js +1 -1
  173. package/dist/localization/messages_zh.esm.js +1 -1
  174. package/dist/localization/messages_zh.js +1 -1
  175. package/dist/localization/messages_zh.min.js +1 -1
  176. package/dist/localization/messages_zh_TW.esm.js +1 -1
  177. package/dist/localization/messages_zh_TW.js +1 -1
  178. package/dist/localization/messages_zh_TW.min.js +1 -1
  179. package/dist/localization/methods_de.esm.js +1 -1
  180. package/dist/localization/methods_de.js +1 -1
  181. package/dist/localization/methods_de.min.js +1 -1
  182. package/dist/localization/methods_es_CL.esm.js +1 -1
  183. package/dist/localization/methods_es_CL.js +1 -1
  184. package/dist/localization/methods_es_CL.min.js +1 -1
  185. package/dist/localization/methods_fi.esm.js +1 -1
  186. package/dist/localization/methods_fi.js +1 -1
  187. package/dist/localization/methods_fi.min.js +1 -1
  188. package/dist/localization/methods_it.esm.js +1 -1
  189. package/dist/localization/methods_it.js +1 -1
  190. package/dist/localization/methods_it.min.js +1 -1
  191. package/dist/localization/methods_nl.esm.js +1 -1
  192. package/dist/localization/methods_nl.js +1 -1
  193. package/dist/localization/methods_nl.min.js +1 -1
  194. package/dist/localization/methods_pt.esm.js +1 -1
  195. package/dist/localization/methods_pt.js +1 -1
  196. package/dist/localization/methods_pt.min.js +1 -1
  197. package/dist/types/defaults.d.ts.map +1 -1
  198. package/dist/types/eventManager.d.ts +2 -0
  199. package/dist/types/eventManager.d.ts.map +1 -1
  200. package/dist/types/index.d.ts +2 -1
  201. package/dist/types/index.d.ts.map +1 -1
  202. package/dist/types/messages.d.ts.map +1 -1
  203. package/dist/types/methods.d.ts.map +1 -1
  204. package/dist/types/rules.d.ts.map +1 -1
  205. package/dist/types/types.d.ts +5 -4
  206. package/dist/types/types.d.ts.map +1 -1
  207. package/dist/types/validator.d.ts.map +1 -1
  208. package/package.json +5 -3
package/README.md CHANGED
@@ -12,91 +12,39 @@ A vanilla JavaScript form validation library - no jQuery required.
12
12
 
13
13
  This library is a partial port of the [jQuery Validation Plugin](https://github.com/jquery-validation/jquery-validation) by Jörn Zaefferer.
14
14
 
15
- ## Features
15
+ ## features
16
16
 
17
- - **17 built-in validation methods** - required, email, URL, number, date, minlength, and more
17
+ - **16 built-in validation methods** - required, email, URL, number, date, minlength, and more
18
+ - **Significantly smaller than jQuery Validation** - Pure vanilla JavaScript with zero dependencies
18
19
  - **Declarative or programmatic API** - Define rules in HTML attributes or JavaScript
19
- - **Zero dependencies** - Pure vanilla JavaScript, no jQuery required
20
+ - **Zero dependencies** - No jQuery required, works everywhere
20
21
  - **Modern ES6+** - ESM and UMD builds for all environments
21
22
  - **Localization support** - Customize error messages/methods for any locale
22
23
 
23
- ## Demo
24
-
25
- [**Try it on CodePen**](https://codepen.io/cadamsmith/pen/NPrxMgQ) - Interactive side-by-side comparison with jQuery Validation
26
-
27
- ## Table of Contents
28
-
29
- - [Installation](#installation)
30
- - [Browser Support](#browser-support)
31
- - [Quick Start](#quick-start)
32
- - [Declarative Validation (HTML Attributes)](#declarative-validation-html-attributes)
33
- - [Programmatic Validation (JavaScript)](#programmatic-validation-javascript)
34
- - [Checking Validation Status](#checking-validation-status)
35
- - [Migrating from jQuery Validation](#migrating-from-jquery-validation)
36
- - [API Method Mapping](#api-method-mapping)
37
- - [Key Differences](#key-differences)
38
- - [Custom Validator Comparison](#custom-validator-comparison)
39
- - [Features Not Included](#features-not-included)
40
- - [Core API](#core-api)
41
- - [dv.validate()](#dvvalidateselector-options)
42
- - [dv.valid()](#dvvalidselector)
43
- - [dv.rules()](#dvrulesselector)
44
- - [dv.addMethod()](#dvaddmethodname-method-message)
45
- - [dv.localize()](#dvlocalizemessages)
46
- - [Built-in Validators](#built-in-validators)
47
- - [Required Field Validators](#required-field-validators)
48
- - [String Format Validators](#string-format-validators)
49
- - [Length Validators](#length-validators)
50
- - [Numeric Validators](#numeric-validators)
51
- - [Comparison Validators](#comparison-validators)
52
- - [Real-world Validator Combinations](#real-world-validator-combinations)
53
- - [Configuration & Customization](#configuration--customization)
54
- - [Error Display Configuration](#error-display-configuration)
55
- - [Event Handling](#event-handling)
56
- - [Validation Behavior](#validation-behavior)
57
- - [Success & Error Callbacks](#success--error-callbacks)
58
- - [Custom Error Messages](#custom-error-messages)
59
- - [Real-world Configuration Examples](#real-world-configuration-examples)
60
- - [Custom Validators](#custom-validators)
61
- - [Custom Validator Basics](#custom-validator-basics)
62
- - [Pattern Matching Examples](#pattern-matching-examples)
63
- - [Conditional/Cross-field Validators](#conditionalcross-field-validators)
64
- - [File Upload Validators](#file-upload-validators)
65
- - [Localization](#localization)
66
- - [Using Localization Builds](#using-localization-builds)
67
- - [Custom Localization](#custom-localization)
68
- - [Coming Soon](#coming-soon)
69
- - [Contributing](#contributing)
70
- - [License](#license)
71
-
72
- ## Installation
24
+ ## examples
73
25
 
74
- ```bash
75
- npm install dino-validation
76
- ```
26
+ Explore interactive examples to see dino-validation in action:
77
27
 
78
- ### ESM vs UMD
28
+ - 📝 **[[quick start]](https://codepen.io/cadamsmith/pen/LEZZegj)**
29
+ Simple contact form showing the minimal setup needed to get started. Includes required fields, email validation, and custom error messages.
79
30
 
80
- Choose the right build for your environment:
31
+ - 🔄 **[[jquery-validation vs dino-validation]](https://codepen.io/cadamsmith/pen/NPrxMgQ)**
32
+ Side-by-side comparison demonstrating feature parity between jquery-validation and dino-validation. See how the same form behaves identically with both libraries.
81
33
 
82
- | Format | Use Case | Import |
83
- | ------- | ---------------------------------------- | --------------------------------------------------------------------------------------------- |
84
- | **ESM** | Modern build tools (Vite, webpack, etc.) | <br/>`import dv from 'dino-validation'` |
85
- | **UMD** | Browsers, legacy builds, CDN | `<script src="https://cdn.jsdelivr.net/npm/dino-validation@VERSION/dist/dv.min.js"></script>` |
34
+ - 📋 **[[declarative config]](https://codepen.io/cadamsmith/pen/EayyoMZ)**
35
+ Define all validation rules using HTML data attributes - no JavaScript configuration needed. Perfect for simple forms.
86
36
 
87
- **ESM Example:**
37
+ - 🔧 **[[custom methods]](https://codepen.io/cadamsmith/pen/wBWWywb)**
38
+ Extend the library's capabilities by creating custom validation methods for specific business requirements. Demonstrates an age verification method with complex date validation logic.
88
39
 
89
- ```javascript
90
- import dv from 'dino-validation';
40
+ - 📍 **[[error placement]](https://codepen.io/cadamsmith/pen/QwEKGrj)**
41
+ Customize where and how validation errors are displayed. Showcases six different error placement strategies: default placement, designated containers, tooltips, grid layouts, error summaries, and inline errors.
91
42
 
92
- const validator = dv.validate('#myForm', {
93
- rules: {
94
- email: { required: true, email: true },
95
- },
96
- });
97
- ```
43
+ ## installation
44
+
45
+ ### umd (cdn)
98
46
 
99
- **UMD Example:**
47
+ For direct browser usage via CDN - no build tools required:
100
48
 
101
49
  ```html
102
50
  <script src="https://cdn.jsdelivr.net/npm/dino-validation@VERSION/dist/dv.min.js"></script>
@@ -109,50 +57,66 @@ const validator = dv.validate('#myForm', {
109
57
  </script>
110
58
  ```
111
59
 
112
- ## Browser Support
60
+ ### esm (npm)
61
+
62
+ For modern build tools (Vite, webpack, Rollup, etc.):
63
+
64
+ ```bash
65
+ npm install dino-validation
66
+ ```
67
+
68
+ ```javascript
69
+ import dv from 'dino-validation';
113
70
 
114
- This library supports all modern evergreen browsers. It requires ES6+ support (browsers from 2017+).
71
+ const validator = dv.validate('#myForm', {
72
+ rules: {
73
+ email: { required: true, email: true },
74
+ },
75
+ });
76
+ ```
115
77
 
116
- **Desktop:**
78
+ ## size comparison
117
79
 
118
- - Chrome/Edge (last 2 versions)
119
- - Firefox (last 2 versions)
120
- - Safari (last 2 versions)
80
+ dino-validation is **significantly smaller** than the jQuery-based alternative:
121
81
 
122
- **Mobile:**
82
+ | Library | Bundle Size (minified + gzipped) | Dependencies |
83
+ | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | --------------- |
84
+ | **dino-validation** | ![](https://img.shields.io/bundlephobia/minzip/dino-validation) | None ✓ |
85
+ | **jquery-validation**<br/>(+ jquery) | ![](https://img.shields.io/bundlephobia/minzip/jquery-validation)<br>![](https://img.shields.io/bundlephobia/minzip/jquery) | Requires jQuery |
123
86
 
124
- - Safari iOS (last 2 versions)
125
- - Chrome Android (last 2 versions)
87
+ 🦖 **Zero dependencies, modern vanilla JavaScript**
126
88
 
127
- Browsers tested in CI using Playwright to ensure cross-browser compatibility.
89
+ _Bundle sizes from [Bundlephobia](https://bundlephobia.com/) (latest published versions)_
128
90
 
129
- ## Quick Start
91
+ ## quick start
130
92
 
131
- ### Declarative Validation (HTML Attributes)
93
+ <details>
94
+ <summary><strong>Declarative Validation (HTML Attributes)</strong></summary>
132
95
 
133
- Define validation rules directly in HTML using data attributes:
96
+ Define validation rules directly in HTML using html attributes:
134
97
 
135
98
  ```html
136
99
  <form id="contactForm">
137
100
  <div>
138
101
  <label for="email">Email:</label>
102
+ <!-- rules: email, required -->
139
103
  <input
140
104
  type="email"
141
105
  name="email"
142
106
  id="email"
143
- data-rule-required="true"
144
- data-rule-email="true"
107
+ required="true"
145
108
  placeholder="your@email.com"
146
109
  />
147
110
  </div>
148
111
 
149
112
  <div>
150
113
  <label for="message">Message:</label>
114
+ <!-- rules: required, minlength -->
151
115
  <textarea
152
116
  name="message"
153
117
  id="message"
154
- data-rule-required="true"
155
- data-rule-minlength="10"
118
+ required="true"
119
+ minlength="10"
156
120
  placeholder="Your message (min 10 characters)"
157
121
  ></textarea>
158
122
  </div>
@@ -166,7 +130,10 @@ Define validation rules directly in HTML using data attributes:
166
130
  </script>
167
131
  ```
168
132
 
169
- ### Programmatic Validation (JavaScript)
133
+ </details>
134
+
135
+ <details>
136
+ <summary><strong>Programmatic Validation (JavaScript)</strong></summary>
170
137
 
171
138
  Define validation rules in JavaScript for more control:
172
139
 
@@ -195,7 +162,10 @@ dv.validate('#contactForm', {
195
162
  });
196
163
  ```
197
164
 
198
- ### Checking Validation Status
165
+ </details>
166
+
167
+ <details>
168
+ <summary><strong>Checking Validation Status</strong></summary>
199
169
 
200
170
  ```javascript
201
171
  // Check if entire form is valid
@@ -209,7 +179,7 @@ if (dv.valid('#email')) {
209
179
  }
210
180
 
211
181
  // Check multiple fields
212
- if (dv.valid(['#email', '#message'])) {
182
+ if (dv.valid('#email, #message')) {
213
183
  console.log('Both fields are valid');
214
184
  }
215
185
 
@@ -220,1601 +190,38 @@ if (dv.valid(emailInput)) {
220
190
  }
221
191
  ```
222
192
 
223
- ## Migrating from jQuery Validation
224
-
225
- If you're familiar with the jQuery Validation Plugin, transitioning to dino-validation is straightforward. The API is intentionally similar to minimize the learning curve.
226
-
227
- ### API Method Mapping
228
-
229
- | jQuery Validation | dino-validation | Notes |
230
- | ------------------------------ | ------------------------------- | -------------------------- |
231
- | `$('#form').validate(options)` | `dv.validate('#form', options)` | Returns Validator instance |
232
- | `$('#form').valid()` | `dv.valid('#form')` | Returns boolean |
233
- | `$('#field').valid()` | `dv.valid('#field')` | Returns boolean |
234
- | `$.validator.addMethod(...)` | `dv.addMethod(...)` | Add custom validators |
235
-
236
- ### Key Differences
237
-
238
- **1. No jQuery Dependency**
239
-
240
- - dino-validation uses pure vanilla JavaScript
241
- - No jQuery chain - methods return values directly
242
-
243
- **2. Validation Method Signature**
244
-
245
- ```javascript
246
- // jQuery Validation
247
- jQuery.validator.addMethod(
248
- 'phone',
249
- function (value, element) {
250
- return this.optional(element) || /^\d{3}-\d{3}-\d{4}$/.test(value);
251
- },
252
- 'Invalid phone format',
253
- );
254
-
255
- // dino-validation
256
- dv.addMethod(
257
- 'phone',
258
- function ({ blank, value, element }) {
259
- return blank || /^\d{3}-\d{3}-\d{4}$/.test(value);
260
- },
261
- 'Invalid phone format',
262
- );
263
- ```
264
-
265
- ### Custom Validator Comparison
266
-
267
- Both libraries support custom validators with similar syntax:
268
-
269
- ```javascript
270
- // jQuery Validation
271
- jQuery.validator.addMethod(
272
- 'usernameAvailable',
273
- function (value, element) {
274
- if (this.optional(element)) return true;
275
-
276
- // Check availability
277
- return checkUsername(value);
278
- },
279
- 'Username is already taken',
280
- );
281
-
282
- // dino-validation
283
- dv.addMethod(
284
- 'usernameAvailable',
285
- function ({ blank, value, element }) {
286
- if (blank) return true;
287
-
288
- // Check availability
289
- return checkUsername(value);
290
- },
291
- 'Username is already taken',
292
- );
293
- ```
294
-
295
- **Key change**: Instead of `this.optional(element)`, use the `blank` parameter.
296
-
297
- ### Features Not Included
298
-
299
- dino-validation is a partial port of jQuery Validation. The following features are **not implemented**:
300
-
301
- **Missing Validators:**
302
-
303
- - `step` - Step increment validation (e.g., multiples of 5)
304
- - `remote` - Server-side AJAX validation
305
-
306
- **Missing Options:**
307
-
308
- - `normalizer` - Transform field values before validation
309
- - `groups` - Group multiple fields into a single error message
310
-
311
- ## Core API
312
-
313
- ### dv.validate(selector, options)
314
-
315
- Creates or retrieves a validator for a form element. If a validator already exists for the element, returns the existing instance.
316
-
317
- **Parameters:**
318
-
319
- - `selector` (string | Element): CSS selector string or HTMLFormElement to validate
320
- - `options` (object, optional): Validation configuration
321
-
322
- **Returns:** Validator instance or undefined if element not found
323
-
324
- **Example:**
325
-
326
- ```javascript
327
- const validator = dv.validate('#myForm', {
328
- rules: {
329
- username: {
330
- required: true,
331
- minlength: 3,
332
- maxlength: 20,
333
- },
334
- email: {
335
- required: true,
336
- email: true,
337
- },
338
- },
339
- messages: {
340
- username: {
341
- required: 'Please enter a username',
342
- minlength: 'Username must be at least 3 characters',
343
- maxlength: 'Username cannot exceed 20 characters',
344
- },
345
- },
346
- errorPlacement: (error, element) => {
347
- // Custom error placement
348
- element.parentElement.appendChild(error);
349
- },
350
- highlight: (element) => {
351
- element.classList.add('is-invalid');
352
- },
353
- unhighlight: (element) => {
354
- element.classList.remove('is-invalid');
355
- },
356
- });
357
-
358
- // Validator instance is cached - calling again returns same instance
359
- const sameValidator = dv.validate('#myForm');
360
- console.log(validator === sameValidator); // true
361
- ```
362
-
363
- ### dv.valid(selector)
364
-
365
- Validates form or form elements and returns whether they are valid. Triggers validation without submitting the form.
366
-
367
- **Parameters:**
368
-
369
- - `selector` (string | HTMLElement | HTMLElement[]): Element(s) to validate
370
-
371
- **Returns:** `true` if all elements are valid, `false` otherwise
372
-
373
- **Examples:**
374
-
375
- ```javascript
376
- // Validate entire form
377
- if (dv.valid('#myForm')) {
378
- console.log('Form is valid!');
379
- } else {
380
- console.log('Form has errors');
381
- }
382
-
383
- // Validate single field
384
- if (dv.valid('#email')) {
385
- console.log('Email is valid');
386
- }
387
-
388
- // Validate multiple fields
389
- if (dv.valid(['#email', '#password'])) {
390
- console.log('Both email and password are valid');
391
- }
392
-
393
- // Use with element reference
394
- const emailInput = document.getElementById('email');
395
- if (dv.valid(emailInput)) {
396
- console.log('Email is valid');
397
- }
398
-
399
- // Validate before enabling submit button
400
- document.getElementById('submitBtn').disabled = !dv.valid('#myForm');
401
- ```
402
-
403
- ### dv.rules(selector)
404
-
405
- Gets the validation rules for an element, merging rules from all sources (HTML attributes, data attributes, CSS classes, and programmatic rules).
406
-
407
- **Parameters:**
408
-
409
- - `selector` (string | HTMLElement): CSS selector string or HTMLElement
410
-
411
- **Returns:** Object containing validation rules for the element
412
-
413
- **Example:**
414
-
415
- ```javascript
416
- // HTML:
417
- // <input id="email" class="required" type="email" minlength="5" />
418
-
419
- const emailRules = dv.rules('#email');
420
- console.log(emailRules);
421
- // { required: true, email: true, minlength: 5 }
422
-
423
- // Use for dynamic rule inspection
424
- if (emailRules.minlength) {
425
- console.log(`Email must be at least ${emailRules.minlength} characters`);
426
- }
427
-
428
- // Check if field is required
429
- if (emailRules.required) {
430
- document.querySelector('label[for="email"]').innerHTML += ' *';
431
- }
432
- ```
433
-
434
- ### dv.addMethod(name, method, message)
435
-
436
- Adds a custom validation method that can be used in validation rules.
437
-
438
- **Parameters:**
439
-
440
- - `name` (string): Name of the validation method
441
- - `method` (function): Validation function that returns `true` if valid
442
- - `message` (string, optional): Default error message
443
-
444
- **Validation Function Signature:**
445
-
446
- ```typescript
447
- function({ blank, value, values, length, element, param }): boolean
448
- ```
449
-
450
- **Input Parameters:**
451
-
452
- - `blank` (boolean): `true` if field is empty
453
- - `value` (string): Field's value
454
- - `values` (string[]): For radio/checkbox groups, array of selected values
455
- - `length` (number): Character count of value
456
- - `element` (FormControlElement): The input element
457
- - `param` (any): Parameter passed in rule definition
458
-
459
- **Examples:**
460
-
461
- **Simple Pattern Matching:**
462
-
463
- ```javascript
464
- dv.addMethod(
465
- 'phone',
466
- function ({ blank, value }) {
467
- return blank || /^\d{3}-\d{3}-\d{4}$/.test(value);
468
- },
469
- 'Please enter a valid phone number (xxx-xxx-xxxx)',
470
- );
471
-
472
- // Use in validation rules
473
- dv.validate('#myForm', {
474
- rules: {
475
- phoneNumber: { phone: true },
476
- },
477
- });
478
- ```
479
-
480
- **Parameterized Validator:**
481
-
482
- ```javascript
483
- dv.addMethod(
484
- 'notContains',
485
- function ({ blank, value, param }) {
486
- return blank || !value.includes(param);
487
- },
488
- 'This field cannot contain "{0}"',
489
- );
490
-
491
- // Use with parameter
492
- dv.validate('#myForm', {
493
- rules: {
494
- bio: { notContains: 'spam' },
495
- },
496
- });
497
- ```
498
-
499
- ### dv.localize(data)
500
-
501
- Replaces default error messages or validation methods with localized versions. Use this for multi-language support.
502
-
503
- **Parameters:**
504
-
505
- - `data` (object): Object containing either localized error messages (string values) or validation methods (function values)
506
- - If values are strings, replaces error messages
507
- - If values are functions, replaces validation methods
508
-
509
- **Returns:** None
510
-
511
- **Example 1: Localize error messages**
512
-
513
- ```javascript
514
- // French localization
515
- dv.localize({
516
- required: 'Ce champ est obligatoire.',
517
- email: 'Veuillez entrer une adresse email valide.',
518
- url: 'Veuillez entrer une URL valide.',
519
- date: 'Veuillez entrer une date valide.',
520
- dateISO: 'Veuillez entrer une date valide (ISO).',
521
- number: 'Veuillez entrer un nombre valide.',
522
- digits: 'Veuillez entrer uniquement des chiffres.',
523
- equalTo: 'Veuillez entrer la même valeur à nouveau.',
524
- maxlength: 'Veuillez entrer au maximum {0} caractères.',
525
- minlength: 'Veuillez entrer au moins {0} caractères.',
526
- rangelength: 'Veuillez entrer une valeur entre {0} et {1} caractères.',
527
- range: 'Veuillez entrer une valeur entre {0} et {1}.',
528
- max: 'Veuillez entrer une valeur inférieure ou égale à {0}.',
529
- min: 'Veuillez entrer une valeur supérieure ou égale à {0}.',
530
- creditcard: 'Veuillez entrer un numéro de carte de crédit valide.',
531
- regex: 'Veuillez entrer une valeur qui correspond au modèle {0}.',
532
- nonalphamin: 'Veuillez entrer au moins {0} caractères non-alphabétiques.',
533
- });
534
- ```
535
-
536
- **Example 2: Partial localization**
537
-
538
- ```javascript
539
- // Only override specific messages
540
- dv.localize({
541
- required: 'This field is mandatory',
542
- email: 'Invalid email format',
543
- });
544
- ```
545
-
546
- ## Built-in Validators
547
-
548
- dino-validation includes 17 built-in validators covering common validation scenarios.
549
-
550
- ### Required Field Validators
551
-
552
- #### `required`
553
-
554
- Validates that the field has a value (is not empty).
555
-
556
- **Parameters:** None
557
-
558
- **Examples:**
559
-
560
- ```html
561
- <!-- HTML attribute -->
562
- <input type="text" name="username" required />
563
-
564
- <!-- Data attribute -->
565
- <input type="text" name="username" data-rule-required="true" />
566
-
567
- <!-- CSS class -->
568
- <input type="text" name="username" class="required" />
569
- ```
570
-
571
- ```javascript
572
- // JavaScript
573
- dv.validate('#myForm', {
574
- rules: {
575
- username: { required: true },
576
- },
577
- });
578
- ```
579
-
580
- **Default message:** "This field is required."
581
-
582
- ### String Format Validators
583
-
584
- #### `email`
585
-
586
- Validates email address format using RFC-compliant regex.
587
-
588
- **Parameters:** None
589
-
590
- **Examples:**
591
-
592
- ```html
593
- <input type="email" name="email" data-rule-email="true" />
594
- ```
595
-
596
- ```javascript
597
- dv.validate('#myForm', {
598
- rules: {
599
- email: { email: true },
600
- },
601
- });
602
- ```
603
-
604
- **Accepts:** `user@example.com`, `first.last@domain.co.uk`, `user+tag@example.com`
605
-
606
- **Important:** Accepts empty values. Combine with `required` for mandatory email fields.
607
-
608
- **Default message:** "Please enter a valid email address."
609
-
610
- ---
611
-
612
- #### `url`
613
-
614
- Validates URL format (HTTP/HTTPS/FTP).
615
-
616
- **Parameters:** None
617
-
618
- **Example:**
619
-
620
- ```javascript
621
- dv.validate('#myForm', {
622
- rules: {
623
- website: { url: true },
624
- },
625
- });
626
- ```
627
-
628
- **Accepts:** `http://example.com`, `https://example.com/path?query=value`, `ftp://files.example.com`
629
-
630
- **Default message:** "Please enter a valid URL."
631
-
632
- ---
633
-
634
- #### `date`
635
-
636
- Validates that the field contains a parseable date string.
637
-
638
- **Parameters:** None
639
-
640
- **Example:**
641
-
642
- ```javascript
643
- dv.validate('#myForm', {
644
- rules: {
645
- birthdate: { date: true },
646
- },
647
- });
648
- ```
649
-
650
- **Accepts:** `12/31/2024`, `2024-12-31`, `December 31, 2024`, any format parseable by `new Date()`
651
-
652
- **Default message:** "Please enter a valid date."
653
-
654
- ---
655
-
656
- #### `dateISO`
657
-
658
- Validates ISO 8601 date format (YYYY-MM-DD or YYYY/MM/DD).
659
-
660
- **Parameters:** None
661
-
662
- **Example:**
663
-
664
- ```html
665
- <input type="date" name="startDate" />
666
- <!-- dateISO automatically applied to type="date" inputs -->
667
- ```
668
-
669
- ```javascript
670
- dv.validate('#myForm', {
671
- rules: {
672
- startDate: { dateISO: true },
673
- },
674
- });
675
- ```
676
-
677
- **Accepts:** `2024-12-31`, `2024/12/31`
678
- **Rejects:** `12/31/2024` (use `date` instead)
679
-
680
- **Default message:** "Please enter a valid date (ISO)."
193
+ </details>
681
194
 
682
- ---
195
+ ## other documentation
683
196
 
684
- #### `creditcard`
197
+ - 📚 **[[api reference]](docs/api-reference.md)**
198
+ Core API methods (`dv.validate`, `dv.valid`, `dv.rules`, etc.)
685
199
 
686
- Validates credit card number using the Luhn algorithm.
200
+ - ✅ **[[built-in validation methods]](docs/methods.md)**
201
+ Complete list of all 16 validation methods
687
202
 
688
- **Parameters:** None
203
+ - 🔧 **[[custom validation methods]](docs/custom-methods.md)**
204
+ Creating custom validation methods
689
205
 
690
- **Example:**
206
+ - 💬 **[[error messages]](docs/error-messages.md)**
207
+ Customizing validation error messages
691
208
 
692
- ```javascript
693
- dv.validate('#myForm', {
694
- rules: {
695
- cardNumber: { creditcard: true },
696
- },
697
- });
698
- ```
699
-
700
- **Accepts:** 13-19 digit numbers, spaces and dashes are stripped automatically
701
-
702
- **Default message:** "Please enter a valid credit card number."
703
-
704
- ---
209
+ - ⚙️ **[[configuration]](docs/configuration.md)**
210
+ Configuration options
705
211
 
706
- #### `digits`
212
+ - 🌍 **[[localization]](docs/localization.md)**
213
+ Support for other locales across the world.
707
214
 
708
- Validates that the field contains only numeric digits (0-9).
709
-
710
- **Parameters:** None
711
-
712
- **Example:**
713
-
714
- ```javascript
715
- dv.validate('#myForm', {
716
- rules: {
717
- zipCode: { digits: true },
718
- },
719
- });
720
- ```
215
+ - 🔄 **[[migrating from jquery-validation]](docs/jqv-migration.md)**
216
+ Differences from **jquery-validation** api
721
217
 
722
- **Accepts:** `12345`, `000`, `99999`
723
- **Rejects:** Decimals, negative numbers, letters (use `number` for decimals)
218
+ ## browser support
724
219
 
725
- **Default message:** "Please enter only digits."
220
+ This library targets modern evergreen browsers with ES6+ support.
726
221
 
727
- ---
728
-
729
- #### `number`
730
-
731
- Validates numeric values including decimals and comma-separated thousands.
732
-
733
- **Parameters:** None
734
-
735
- **Example:**
736
-
737
- ```javascript
738
- dv.validate('#myForm', {
739
- rules: {
740
- amount: { number: true },
741
- },
742
- });
743
- ```
744
-
745
- **Accepts:** `100`, `100.50`, `1,000.00`, `-50.5`
746
-
747
- **Default message:** "Please enter a valid number."
748
-
749
- ### Length Validators
750
-
751
- #### `minlength`
752
-
753
- Validates minimum string length.
754
-
755
- **Parameters:** `integer` - minimum character count
756
-
757
- **Examples:**
758
-
759
- ```html
760
- <input type="text" name="username" minlength="3" />
761
- <!-- or -->
762
- <input type="text" name="username" data-rule-minlength="3" />
763
- ```
764
-
765
- ```javascript
766
- dv.validate('#myForm', {
767
- rules: {
768
- username: { minlength: 3 },
769
- },
770
- });
771
- ```
772
-
773
- **Works with:** Character count (not bytes), applies to text inputs and textareas
774
-
775
- **Default message:** "Please enter at least {0} characters."
776
-
777
- ---
778
-
779
- #### `maxlength`
780
-
781
- Validates maximum string length.
782
-
783
- **Parameters:** `integer` - maximum character count
784
-
785
- **Example:**
786
-
787
- ```javascript
788
- dv.validate('#myForm', {
789
- rules: {
790
- username: {
791
- minlength: 3,
792
- maxlength: 20,
793
- },
794
- },
795
- });
796
- ```
797
-
798
- **Default message:** "Please enter no more than {0} characters."
799
-
800
- ---
801
-
802
- #### `rangelength`
803
-
804
- Validates string length is within a range.
805
-
806
- **Parameters:** `[min, max]` - array with minimum and maximum character counts
807
-
808
- **Example:**
809
-
810
- ```javascript
811
- dv.validate('#myForm', {
812
- rules: {
813
- bio: { rangelength: [10, 500] },
814
- },
815
- messages: {
816
- bio: 'Your bio must be between 10 and 500 characters',
817
- },
818
- });
819
- ```
820
-
821
- **Default message:** "Please enter a value between {0} and {1} characters long."
822
-
823
- ### Numeric Validators
824
-
825
- #### `min`
826
-
827
- Validates that numeric value is greater than or equal to minimum.
828
-
829
- **Parameters:** `number` - minimum value
830
-
831
- **Examples:**
832
-
833
- ```html
834
- <input type="number" name="age" min="18" />
835
- ```
836
-
837
- ```javascript
838
- dv.validate('#myForm', {
839
- rules: {
840
- age: { min: 18 },
841
- },
842
- });
843
- ```
844
-
845
- **Default message:** "Please enter a value greater than or equal to {0}."
846
-
847
- ---
848
-
849
- #### `max`
850
-
851
- Validates that numeric value is less than or equal to maximum.
852
-
853
- **Parameters:** `number` - maximum value
854
-
855
- **Example:**
856
-
857
- ```javascript
858
- dv.validate('#myForm', {
859
- rules: {
860
- percentage: { max: 100 },
861
- },
862
- });
863
- ```
864
-
865
- **Default message:** "Please enter a value less than or equal to {0}."
866
-
867
- ---
868
-
869
- #### `range`
870
-
871
- Validates that numeric value is within a range.
872
-
873
- **Parameters:** `[min, max]` - array with minimum and maximum values
874
-
875
- **Example:**
876
-
877
- ```javascript
878
- dv.validate('#myForm', {
879
- rules: {
880
- rating: { range: [1, 5] },
881
- },
882
- });
883
- ```
884
-
885
- **Default message:** "Please enter a value between {0} and {1}."
886
-
887
- ### Comparison Validators
888
-
889
- #### `equalTo`
890
-
891
- Validates that field value matches another field's value (e.g., password confirmation).
892
-
893
- **Parameters:** `string` - CSS selector of target field
894
-
895
- **Examples:**
896
-
897
- ```html
898
- <input type="password" name="password" id="password" />
899
- <input type="password" name="confirmPassword" data-rule-equalto="#password" />
900
- ```
901
-
902
- ```javascript
903
- dv.validate('#myForm', {
904
- rules: {
905
- password: { required: true, minlength: 8 },
906
- confirmPassword: {
907
- required: true,
908
- equalTo: '#password',
909
- },
910
- },
911
- messages: {
912
- confirmPassword: {
913
- equalTo: 'Passwords do not match',
914
- },
915
- },
916
- });
917
- ```
918
-
919
- **Default message:** "Please enter the same value again."
920
-
921
- ---
922
-
923
- #### `regex`
924
-
925
- Validates that value matches a regular expression pattern.
926
-
927
- **Parameters:** `string` - regex pattern (must match entire string)
928
-
929
- **Example:**
930
-
931
- ```javascript
932
- dv.addMethod(
933
- 'regex',
934
- function ({ blank, value, param }) {
935
- if (blank) return true;
936
- const match = new RegExp(param).exec(value);
937
- return !!match && match.index === 0 && match[0].length === value.length;
938
- },
939
- 'Please enter a value matching the pattern {0}.',
940
- );
941
-
942
- dv.validate('#myForm', {
943
- rules: {
944
- username: { regex: '^[a-zA-Z0-9_-]+$' },
945
- },
946
- });
947
- ```
948
-
949
- **Note:** Pattern must match from start to end of string.
950
-
951
- **Default message:** "Please enter a value that matches the pattern {0}."
952
-
953
- ---
954
-
955
- #### `nonalphamin`
956
-
957
- Validates minimum count of non-alphanumeric characters (for password strength).
958
-
959
- **Parameters:** `integer` - minimum number of special characters required
960
-
961
- **Example:**
962
-
963
- ```javascript
964
- dv.validate('#myForm', {
965
- rules: {
966
- password: {
967
- required: true,
968
- minlength: 8,
969
- nonalphamin: 1, // At least 1 special character
970
- },
971
- },
972
- });
973
- ```
974
-
975
- **Common special characters:** `!@#$%^&*()_+-=[]{}|;:,.<>?`
976
-
977
- **Default message:** "Please enter at least {0} non-alphabetic characters."
978
-
979
- ### Real-world Validator Combinations
980
-
981
- **Username Validation:**
982
-
983
- ```javascript
984
- username: {
985
- required: true,
986
- minlength: 3,
987
- maxlength: 20,
988
- regex: '^[a-zA-Z0-9_-]+$'
989
- }
990
- ```
991
-
992
- **Strong Password Validation:**
993
-
994
- ```javascript
995
- password: {
996
- required: true,
997
- minlength: 12,
998
- nonalphamin: 2 // At least 2 special characters
999
- }
1000
- ```
1001
-
1002
- **Age Validation:**
1003
-
1004
- ```javascript
1005
- age: {
1006
- required: true,
1007
- number: true,
1008
- min: 18,
1009
- max: 120
1010
- }
1011
- ```
1012
-
1013
- **Discount Code Validation:**
1014
-
1015
- ```javascript
1016
- discountCode: {
1017
- minlength: 5,
1018
- maxlength: 10,
1019
- regex: '^[A-Z0-9]+$' // Uppercase letters and numbers only
1020
- }
1021
- ```
1022
-
1023
- **Email with Confirmation:**
1024
-
1025
- ```javascript
1026
- rules: {
1027
- email: {
1028
- required: true,
1029
- email: true
1030
- },
1031
- emailConfirm: {
1032
- required: true,
1033
- equalTo: '#email'
1034
- }
1035
- }
1036
- ```
1037
-
1038
- ## Configuration & Customization
1039
-
1040
- dino-validation is highly customizable. Control how errors are displayed, when validation occurs, and how fields are styled.
1041
-
1042
- ### Error Display Configuration
1043
-
1044
- #### `errorClass` and `validClass`
1045
-
1046
- CSS classes applied to invalid/valid fields.
1047
-
1048
- **Defaults:** `errorClass: 'error'`, `validClass: 'valid'`
1049
-
1050
- **Example:**
1051
-
1052
- ```javascript
1053
- dv.validate('#myForm', {
1054
- errorClass: 'is-invalid',
1055
- validClass: 'is-valid',
1056
- });
1057
- ```
1058
-
1059
- **CSS:**
1060
-
1061
- ```css
1062
- .is-invalid {
1063
- border-color: #dc3545;
1064
- background-color: #fff5f5;
1065
- }
1066
-
1067
- .is-valid {
1068
- border-color: #28a745;
1069
- }
1070
- ```
1071
-
1072
- ---
1073
-
1074
- #### `errorElement` and `wrapper`
1075
-
1076
- Control the HTML structure of error messages.
1077
-
1078
- **Defaults:** `errorElement: 'label'`, `wrapper: null`
1079
-
1080
- **Example:**
1081
-
1082
- ```javascript
1083
- dv.validate('#myForm', {
1084
- errorElement: 'span',
1085
- wrapper: 'div',
1086
- });
1087
- ```
1088
-
1089
- **Renders as:**
1090
-
1091
- ```html
1092
- <div><span class="error">Error message here</span></div>
1093
- ```
1094
-
1095
- ---
1096
-
1097
- #### `errorPlacement`
1098
-
1099
- Custom function to position error messages.
1100
-
1101
- **Signature:** `(error: HTMLElement, element: FormControlElement) => void`
1102
-
1103
- **Default behavior:** Appends error after the field
1104
-
1105
- **Example 1: Place in specific container**
1106
-
1107
- ```javascript
1108
- dv.validate('#myForm', {
1109
- errorPlacement: (error, element) => {
1110
- const fieldName = element.name;
1111
- const errorContainer = document.getElementById(`error-${fieldName}`);
1112
- errorContainer.appendChild(error);
1113
- },
1114
- });
1115
- ```
1116
-
1117
- **Example 2: Place in form row**
1118
-
1119
- ```javascript
1120
- dv.validate('#myForm', {
1121
- errorPlacement: (error, element) => {
1122
- const row = element.closest('.form-row');
1123
- row.querySelector('.error-target').appendChild(error);
1124
- },
1125
- });
1126
- ```
1127
-
1128
- **Example 3: Tooltip-style errors**
1129
-
1130
- ```javascript
1131
- dv.validate('#myForm', {
1132
- errorPlacement: (error, element) => {
1133
- error.classList.add('tooltip');
1134
- element.parentElement.appendChild(error);
1135
- },
1136
- });
1137
- ```
1138
-
1139
- ---
1140
-
1141
- #### `highlight` and `unhighlight`
1142
-
1143
- Custom functions to add/remove error styling.
1144
-
1145
- **Signature:** `(element: FormControlElement, errorClasses: string[], validClasses: string[]) => void`
1146
-
1147
- **Default behavior:** Adds/removes `errorClass` and `validClass`
1148
-
1149
- **Example 1: Bootstrap styling**
1150
-
1151
- ```javascript
1152
- dv.validate('#myForm', {
1153
- highlight: (element) => {
1154
- element.classList.add('is-invalid');
1155
- element.closest('.form-group')?.classList.add('has-error');
1156
- },
1157
- unhighlight: (element) => {
1158
- element.classList.remove('is-invalid');
1159
- element.closest('.form-group')?.classList.remove('has-error');
1160
- },
1161
- });
1162
- ```
1163
-
1164
- **Example 2: Custom validation states**
1165
-
1166
- ```javascript
1167
- dv.validate('#myForm', {
1168
- highlight: (element, errorClasses) => {
1169
- element.classList.add(...errorClasses);
1170
- element.setAttribute('aria-invalid', 'true');
1171
- },
1172
- unhighlight: (element, errorClasses) => {
1173
- element.classList.remove(...errorClasses);
1174
- element.setAttribute('aria-invalid', 'false');
1175
- },
1176
- });
1177
- ```
1178
-
1179
- ---
1180
-
1181
- #### `errorLabelContainer` and `errorContainer`
1182
-
1183
- Group error messages in a single location.
1184
-
1185
- **Example: Error summary at top of form**
1186
-
1187
- ```html
1188
- <div id="errorSummary" style="display: none;">
1189
- <h3>Please fix the following errors:</h3>
1190
- <ul id="errorList"></ul>
1191
- </div>
1192
-
1193
- <form id="myForm">
1194
- <!-- form fields -->
1195
- </form>
1196
- ```
1197
-
1198
- ```javascript
1199
- dv.validate('#myForm', {
1200
- errorContainer: '#errorSummary',
1201
- errorLabelContainer: '#errorList ul',
1202
- });
1203
- ```
1204
-
1205
- ### Event Handling
1206
-
1207
- Control when validation occurs.
1208
-
1209
- #### `onfocusout`, `onkeyup`, `onclick`, `onfocusin`
1210
-
1211
- Can be boolean (enable/disable) or custom function.
1212
-
1213
- **Defaults:** `onfocusout: true`, others: `false`
1214
-
1215
- **Example 1: Validate on blur (recommended for UX)**
1216
-
1217
- ```javascript
1218
- dv.validate('#myForm', {
1219
- onfocusout: (element) => {
1220
- // Validate when user leaves field
1221
- dv.valid(element);
1222
- },
1223
- });
1224
- ```
1225
-
1226
- **Example 2: Real-time validation with debounce**
1227
-
1228
- ```javascript
1229
- let timeoutId;
1230
- dv.validate('#myForm', {
1231
- onkeyup: (element) => {
1232
- clearTimeout(timeoutId);
1233
- timeoutId = setTimeout(() => {
1234
- dv.valid(element);
1235
- }, 300); // Wait 300ms after last keystroke
1236
- },
1237
- });
1238
- ```
1239
-
1240
- **Example 3: Disable all event validation**
1241
-
1242
- ```javascript
1243
- dv.validate('#myForm', {
1244
- onfocusout: false,
1245
- onkeyup: false,
1246
- onclick: false,
1247
- });
1248
- ```
1249
-
1250
- ---
1251
-
1252
- #### `onsubmit`
1253
-
1254
- Controls whether form validates on submit.
1255
-
1256
- **Default:** `true`
1257
-
1258
- **Example: Manual validation control**
1259
-
1260
- ```javascript
1261
- const validator = dv.validate('#myForm', { onsubmit: false });
1262
-
1263
- document.getElementById('submitBtn').addEventListener('click', () => {
1264
- if (validator.form()) {
1265
- // Validation passed, submit form
1266
- document.getElementById('myForm').submit();
1267
- }
1268
- });
1269
- ```
1270
-
1271
- ### Validation Behavior
1272
-
1273
- #### `ignore`
1274
-
1275
- CSS selector for elements to ignore during validation.
1276
-
1277
- **Default:** `':hidden'` (skip hidden fields)
1278
-
1279
- **Example: Also ignore disabled fields**
1280
-
1281
- ```javascript
1282
- dv.validate('#myForm', {
1283
- ignore: ':hidden, :disabled',
1284
- });
1285
- ```
1286
-
1287
- ---
1288
-
1289
- #### `focusCleanup`
1290
-
1291
- Remove error class when field gets focus.
1292
-
1293
- **Default:** `false`
1294
-
1295
- **Example:**
1296
-
1297
- ```javascript
1298
- dv.validate('#myForm', {
1299
- focusCleanup: true,
1300
- });
1301
- ```
1302
-
1303
- ---
1304
-
1305
- #### `escapeHtml`
1306
-
1307
- Escape HTML in error messages to prevent XSS attacks.
1308
-
1309
- **Default:** `false`
1310
-
1311
- **Important:** Enable if error messages come from user input.
1312
-
1313
- **Example:**
1314
-
1315
- ```javascript
1316
- dv.validate('#myForm', {
1317
- escapeHtml: true, // Prevents <script> tags in custom messages
1318
- });
1319
- ```
1320
-
1321
- ---
1322
-
1323
- #### `debug`
1324
-
1325
- Enable debug mode (prevents form submission, useful during development).
1326
-
1327
- **Default:** `false`
1328
-
1329
- **Example:**
1330
-
1331
- ```javascript
1332
- dv.validate('#myForm', {
1333
- debug: true, // Form won't submit, check console for validation info
1334
- });
1335
- ```
1336
-
1337
- ### Success & Error Callbacks
1338
-
1339
- #### `success`
1340
-
1341
- Callback when field passes validation. Can be a CSS class or function.
1342
-
1343
- **Example 1: Add success class**
1344
-
1345
- ```javascript
1346
- dv.validate('#myForm', {
1347
- success: 'valid-field',
1348
- });
1349
- ```
1350
-
1351
- **Example 2: Custom success handler**
1352
-
1353
- ```javascript
1354
- dv.validate('#myForm', {
1355
- success: (labels, element) => {
1356
- labels.forEach((label) => {
1357
- label.classList.add('success-msg');
1358
- label.textContent = '✓ Looks good!';
1359
- });
1360
- },
1361
- });
1362
- ```
1363
-
1364
- ---
1365
-
1366
- #### `invalidHandler`
1367
-
1368
- Callback when form submission fails validation.
1369
-
1370
- **Signature:** `(event: CustomEvent<ValidationError[]>) => void`
1371
-
1372
- **Example: Display error summary**
1373
-
1374
- ```javascript
1375
- dv.validate('#myForm', {
1376
- invalidHandler: (event) => {
1377
- const errors = event.detail;
1378
- console.log(`Form has ${errors.length} error(s)`);
1379
-
1380
- // Display error summary
1381
- const errorList = document.getElementById('errorSummary');
1382
- errorList.innerHTML =
1383
- '<h4>Please fix the following:</h4>' +
1384
- errors
1385
- .map((err) => `<li>${err.element.name}: ${err.message}</li>`)
1386
- .join('');
1387
- },
1388
- });
1389
- ```
1390
-
1391
- ### Custom Error Messages
1392
-
1393
- Three ways to specify custom error messages:
1394
-
1395
- **1. Per-field in config object**
1396
-
1397
- ```javascript
1398
- dv.validate('#myForm', {
1399
- rules: {
1400
- email: { required: true, email: true },
1401
- },
1402
- messages: {
1403
- email: {
1404
- required: 'Please enter your email address',
1405
- email: 'Invalid email format',
1406
- },
1407
- },
1408
- });
1409
- ```
1410
-
1411
- **2. Data attributes**
1412
-
1413
- ```html
1414
- <input
1415
- type="email"
1416
- name="email"
1417
- data-rule-required="true"
1418
- data-rule-email="true"
1419
- data-msg-required="Email is required"
1420
- data-msg-email="Please enter a valid email"
1421
- />
1422
- ```
1423
-
1424
- **3. Parameterized messages**
1425
-
1426
- ```javascript
1427
- dv.validate('#myForm', {
1428
- rules: {
1429
- username: { minlength: 5, maxlength: 20 },
1430
- },
1431
- messages: {
1432
- username: {
1433
- minlength: 'Username must be at least {0} characters',
1434
- maxlength: 'Username cannot exceed {0} characters',
1435
- },
1436
- },
1437
- });
1438
- ```
1439
-
1440
- ### Real-world Configuration Examples
1441
-
1442
- **Bootstrap Form Styling:**
1443
-
1444
- ```javascript
1445
- dv.validate('#myForm', {
1446
- errorClass: 'is-invalid',
1447
- validClass: 'is-valid',
1448
- errorElement: 'div',
1449
- errorPlacement: (error, element) => {
1450
- error.classList.add('invalid-feedback', 'd-block');
1451
- element.parentElement.appendChild(error);
1452
- },
1453
- highlight: (element) => {
1454
- element.classList.add('is-invalid');
1455
- },
1456
- unhighlight: (element) => {
1457
- element.classList.remove('is-invalid');
1458
- },
1459
- });
1460
- ```
1461
-
1462
- **Inline Validation with Real-time Feedback:**
1463
-
1464
- ```javascript
1465
- dv.validate('#myForm', {
1466
- onfocusout: (element) => dv.valid(element),
1467
- onkeyup: (element) => dv.valid(element),
1468
- errorElement: 'span',
1469
- errorPlacement: (error, element) => {
1470
- error.classList.add('help-text');
1471
- element.parentElement.appendChild(error);
1472
- },
1473
- highlight: (element) => {
1474
- element.classList.add('error');
1475
- },
1476
- unhighlight: (element) => {
1477
- element.classList.remove('error');
1478
- },
1479
- });
1480
- ```
1481
-
1482
- **Form Submission with Loading Spinner:**
1483
-
1484
- ```javascript
1485
- dv.validate('#myForm', {
1486
- invalidHandler: (event) => {
1487
- // Stop spinner if validation fails
1488
- document.querySelector('[type="submit"]').disabled = false;
1489
- document.querySelector('.spinner').style.display = 'none';
1490
- },
1491
- });
1492
-
1493
- document.getElementById('myForm').addEventListener('submit', (e) => {
1494
- if (!dv.valid('#myForm')) {
1495
- e.preventDefault();
1496
- return;
1497
- }
1498
-
1499
- // Show spinner while submitting
1500
- document.querySelector('[type="submit"]').disabled = true;
1501
- document.querySelector('.spinner').style.display = 'inline-block';
1502
- });
1503
- ```
1504
-
1505
- ## Custom Validators
1506
-
1507
- Extend dino-validation with custom validation rules for your specific needs.
1508
-
1509
- ### Custom Validator Basics
1510
-
1511
- **Validator Function Signature:**
1512
-
1513
- ```typescript
1514
- function({ blank, value, values, length, element, param }): boolean
1515
- ```
1516
-
1517
- **Input Parameters:**
1518
-
1519
- - `blank` (boolean): `true` if field is empty
1520
- - `value` (string): Field's value
1521
- - `values` (string[]): For radio/checkbox groups, array of selected values
1522
- - `length` (number): Character count of value
1523
- - `element` (FormControlElement): The input element
1524
- - `param` (any): Parameter passed in rule definition
1525
-
1526
- **Return Value:** `true` if valid, `false` if invalid
1527
-
1528
- ### Pattern Matching Examples
1529
-
1530
- **URL Slug Validator:**
1531
-
1532
- ```javascript
1533
- dv.addMethod(
1534
- 'slug',
1535
- function ({ blank, value }) {
1536
- // Lowercase letters, numbers, and hyphens only
1537
- return blank || /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value);
1538
- },
1539
- 'URL slug must contain lowercase letters, numbers, and hyphens only',
1540
- );
1541
-
1542
- // Usage
1543
- dv.validate('#myForm', {
1544
- rules: {
1545
- permalink: { slug: true },
1546
- },
1547
- });
1548
- ```
1549
-
1550
- **Username Validator:**
1551
-
1552
- ```javascript
1553
- dv.addMethod(
1554
- 'username',
1555
- function ({ blank, value }) {
1556
- // 3-20 chars, letters/numbers/_/-, must start with letter
1557
- return blank || /^[a-zA-Z][a-zA-Z0-9_-]{2,19}$/.test(value);
1558
- },
1559
- 'Username must start with a letter and be 3-20 characters (alphanumeric, _, -)',
1560
- );
1561
-
1562
- // Usage
1563
- dv.validate('#myForm', {
1564
- rules: {
1565
- username: {
1566
- required: true,
1567
- username: true,
1568
- },
1569
- },
1570
- });
1571
- ```
1572
-
1573
- **Strong Password Validator:**
1574
-
1575
- ```javascript
1576
- dv.addMethod(
1577
- 'strongPassword',
1578
- function ({ blank, value }) {
1579
- if (blank) return true;
1580
-
1581
- const hasUppercase = /[A-Z]/.test(value);
1582
- const hasLowercase = /[a-z]/.test(value);
1583
- const hasNumber = /\d/.test(value);
1584
- const hasSpecial = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value);
1585
- const isLongEnough = value.length >= 12;
1586
-
1587
- return (
1588
- hasUppercase && hasLowercase && hasNumber && hasSpecial && isLongEnough
1589
- );
1590
- },
1591
- 'Password must contain uppercase, lowercase, number, special character, and be 12+ characters',
1592
- );
1593
-
1594
- // Usage
1595
- dv.validate('#myForm', {
1596
- rules: {
1597
- password: {
1598
- required: true,
1599
- strongPassword: true,
1600
- },
1601
- },
1602
- });
1603
- ```
1604
-
1605
- ### Conditional/Cross-field Validators
1606
-
1607
- **Greater Than Validator:**
1608
-
1609
- ```javascript
1610
- dv.addMethod(
1611
- 'greaterThan',
1612
- function ({ blank, value, param }) {
1613
- if (blank) return true;
1614
-
1615
- const otherField = document.querySelector(param);
1616
- return parseFloat(value) > parseFloat(otherField.value);
1617
- },
1618
- 'This value must be greater than {0}',
1619
- );
1620
-
1621
- // Usage: End date after start date
1622
- dv.validate('#myForm', {
1623
- rules: {
1624
- startDate: { required: true, date: true },
1625
- endDate: {
1626
- required: true,
1627
- date: true,
1628
- greaterThan: '#startDate',
1629
- },
1630
- },
1631
- messages: {
1632
- endDate: {
1633
- greaterThan: 'End date must be after start date',
1634
- },
1635
- },
1636
- });
1637
- ```
1638
-
1639
- **Date Range Validator:**
1640
-
1641
- ```javascript
1642
- dv.addMethod(
1643
- 'dateAfter',
1644
- function ({ blank, value, param }) {
1645
- if (blank) return true;
1646
-
1647
- const otherDate = new Date(document.querySelector(param).value);
1648
- return new Date(value) > otherDate;
1649
- },
1650
- 'End date must be after start date',
1651
- );
1652
-
1653
- // Usage
1654
- dv.validate('#myForm', {
1655
- rules: {
1656
- startDate: { required: true, date: true },
1657
- endDate: {
1658
- required: true,
1659
- dateAfter: '#startDate',
1660
- },
1661
- },
1662
- });
1663
- ```
1664
-
1665
- **Conditional Required (depends on another field):**
1666
-
1667
- ```javascript
1668
- dv.addMethod(
1669
- 'requiredIf',
1670
- function ({ value, param }) {
1671
- const dependentField = document.querySelector(param.selector);
1672
- const dependentValue = param.value;
1673
-
1674
- if (dependentField.value === dependentValue) {
1675
- // This field is required
1676
- return value.trim().length > 0;
1677
- }
1678
- return true; // Not required
1679
- },
1680
- 'This field is required',
1681
- );
1682
-
1683
- // Usage: "Other" details required only if category is "other"
1684
- dv.validate('#myForm', {
1685
- rules: {
1686
- category: { required: true },
1687
- otherDetails: {
1688
- requiredIf: {
1689
- selector: '#category',
1690
- value: 'other',
1691
- },
1692
- },
1693
- },
1694
- });
1695
- ```
1696
-
1697
- ### File Upload Validators
1698
-
1699
- **File Type Validator:**
1700
-
1701
- ```javascript
1702
- dv.addMethod(
1703
- 'fileType',
1704
- function ({ blank, element, param }) {
1705
- if (blank || !element.files?.length) return true;
1706
-
1707
- const file = element.files[0];
1708
- const allowedTypes = param.split(',').map((t) => t.trim());
1709
-
1710
- return allowedTypes.some((type) => file.type.startsWith(type));
1711
- },
1712
- 'Please upload a file of type: {0}',
1713
- );
1714
-
1715
- // Usage
1716
- dv.validate('#myForm', {
1717
- rules: {
1718
- profileImage: {
1719
- required: true,
1720
- fileType: 'image/jpeg,image/png,image/webp',
1721
- },
1722
- },
1723
- messages: {
1724
- profileImage: {
1725
- fileType: 'Please upload a JPEG, PNG, or WebP image',
1726
- },
1727
- },
1728
- });
1729
- ```
1730
-
1731
- **File Size Validator:**
1732
-
1733
- ```javascript
1734
- dv.addMethod(
1735
- 'fileSize',
1736
- function ({ blank, element, param }) {
1737
- if (blank || !element.files?.length) return true;
1738
-
1739
- const file = element.files[0];
1740
- const maxSizeInBytes = param * 1024 * 1024; // Convert MB to bytes
1741
-
1742
- return file.size <= maxSizeInBytes;
1743
- },
1744
- 'File must be smaller than {0}MB',
1745
- );
1746
-
1747
- // Usage: Max 10MB
1748
- dv.validate('#myForm', {
1749
- rules: {
1750
- document: {
1751
- required: true,
1752
- fileSize: 10,
1753
- },
1754
- },
1755
- });
1756
- ```
1757
-
1758
- ## Localization
1759
-
1760
- dino-validation supports multiple languages.
1761
-
1762
- You can use pre-built localization files provided by the library, or create your own custom translations using `dv.localize()`.
1763
-
1764
- ### Using Localization Builds
1765
-
1766
- dino-validation includes pre-built localization files.
1767
-
1768
- **French (UMD):**
1769
-
1770
- ```html
1771
- <script src="dist/dv.min.js"></script>
1772
- <script src="dist/localization/messages_fr.min.js"></script>
1773
-
1774
- <script>
1775
- // French messages are now loaded
1776
- dv.validate('#myForm', { ... });
1777
- </script>
1778
- ```
1779
-
1780
- **French (ESM):**
1781
-
1782
- ```javascript
1783
- import dv from 'dino-validation';
1784
- import 'dino-validation/dist/localization/messages_fr.esm.js';
1785
-
1786
- // French messages are now loaded
1787
- dv.validate('#myForm', { ... });
1788
- ```
1789
-
1790
- ### Custom Localization
1791
-
1792
- Use `dv.localize()` to translate error messages yourself.
1793
-
1794
- ```javascript
1795
- // Custom messages (use any language or wording you want)
1796
- dv.localize({
1797
- required: 'Beep boop! This field cannot be empty.',
1798
- email: "Beep! That doesn't look like a valid email address.",
1799
- url: 'Boop! Please enter a valid URL.',
1800
- date: 'Beep boop! Invalid date detected.',
1801
- dateISO: 'Boop! Date must be in ISO format (YYYY-MM-DD).',
1802
- number: 'Beep! Numbers only, please.',
1803
- digits: 'Boop boop! Only digits allowed (0-9).',
1804
- equalTo: 'Beep! These values must match.',
1805
- maxlength: 'Boop! Maximum {0} characters allowed.',
1806
- minlength: 'Beep! Minimum {0} characters required.',
1807
- rangelength: 'Beep boop! Must be between {0} and {1} characters.',
1808
- range: 'Boop! Value must be between {0} and {1}.',
1809
- max: 'Beep! Value must be {0} or less.',
1810
- min: 'Boop! Value must be {0} or more.',
1811
- creditcard: 'Beep boop! Invalid credit card number.',
1812
- regex: 'Boop! Must match pattern: {0}.',
1813
- nonalphamin: 'Beep! At least {0} special characters required.',
1814
- });
1815
- ```
222
+ The last 2 versions of the following are supported: `[Chrome, Edge, Firefox, Safari, Safari iOS, Chrome Android]`
1816
223
 
1817
- ## Coming Soon
224
+ ## coming soon
1818
225
 
1819
226
  The following features are planned for future releases:
1820
227
 
@@ -1823,7 +230,7 @@ The following features are planned for future releases:
1823
230
  - **Documentation site** - Dedicated documentation website with interactive examples and improved navigation
1824
231
  - **Unobtrusive validation support** - Support for `data-val-*` attributes to enable seamless integration with server-side frameworks (ASP.NET MVC, etc.) where validation rules defined in server-side model annotations are automatically applied client-side
1825
232
 
1826
- ## Contributing
233
+ ## contributing
1827
234
 
1828
235
  Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on:
1829
236
 
@@ -1831,7 +238,7 @@ Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for gui
1831
238
  - Making changes and running tests
1832
239
  - Conventions & Pull request process
1833
240
 
1834
- ## License
241
+ ## license
1835
242
 
1836
243
  MIT License - See [LICENSE](LICENSE) file for details.
1837
244