@lion/ui 0.0.2 → 0.0.3

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 (263) hide show
  1. package/components/core/test/SlotMixin.test.js +28 -21
  2. package/components/localize/src/number/parseNumber.js +15 -36
  3. package/components/localize/test/number/parseNumber.test.js +3 -12
  4. package/dist-types/components/localize/src/number/parseNumber.d.ts.map +1 -1
  5. package/dist-types/tsconfig.tsbuildinfo +1 -1
  6. package/docs/components/accordion/index.md +3 -0
  7. package/docs/components/accordion/overview.md +129 -0
  8. package/docs/components/accordion/reference.md +47 -0
  9. package/docs/components/accordion/use-cases.md +252 -0
  10. package/docs/components/button/examples.md +30 -0
  11. package/docs/components/button/index.md +3 -0
  12. package/docs/components/button/overview.md +30 -0
  13. package/docs/components/button/src/icon.svg.js +5 -0
  14. package/docs/components/button/use-cases.md +106 -0
  15. package/docs/components/calendar/index.md +3 -0
  16. package/docs/components/calendar/overview.md +49 -0
  17. package/docs/components/calendar/use-cases.md +192 -0
  18. package/docs/components/checkbox-group/index.md +3 -0
  19. package/docs/components/checkbox-group/overview.md +40 -0
  20. package/docs/components/checkbox-group/use-cases.md +256 -0
  21. package/docs/components/collapsible/assets/CustomCollapsible.js +113 -0
  22. package/docs/components/collapsible/assets/applyDemoCollapsibleStyles.js +37 -0
  23. package/docs/components/collapsible/examples.md +83 -0
  24. package/docs/components/collapsible/index.md +3 -0
  25. package/docs/components/collapsible/overview.md +39 -0
  26. package/docs/components/collapsible/use-cases.md +79 -0
  27. package/docs/components/combobox/examples.md +153 -0
  28. package/docs/components/combobox/index.md +3 -0
  29. package/docs/components/combobox/overview.md +51 -0
  30. package/docs/components/combobox/src/LinkMixin.js +60 -0
  31. package/docs/components/combobox/src/demo-selection-display.js +191 -0
  32. package/docs/components/combobox/src/gh-combobox/gh-button.js +69 -0
  33. package/docs/components/combobox/src/gh-combobox/gh-combobox.js +508 -0
  34. package/docs/components/combobox/src/google-combobox/assets/google-clear-icon.js +9 -0
  35. package/docs/components/combobox/src/google-combobox/assets/google-search-icon.js +9 -0
  36. package/docs/components/combobox/src/google-combobox/assets/google-voice-search-icon.js +19 -0
  37. package/docs/components/combobox/src/google-combobox/assets/googlelogo_color_272x92dp.png +0 -0
  38. package/docs/components/combobox/src/google-combobox/google-combobox.js +460 -0
  39. package/docs/components/combobox/src/lazyRender.js +29 -0
  40. package/docs/components/combobox/src/levenshtein.js +95 -0
  41. package/docs/components/combobox/src/md-combobox/MdFieldMixin.js +341 -0
  42. package/docs/components/combobox/src/md-combobox/md-combobox.js +89 -0
  43. package/docs/components/combobox/src/md-combobox/md-input.js +5 -0
  44. package/docs/components/combobox/src/md-combobox/style/load-roboto.js +6 -0
  45. package/docs/components/combobox/src/md-combobox/style/md-ripple.js +81 -0
  46. package/docs/components/combobox/src/wa-combobox/wa-combobox.js +368 -0
  47. package/docs/components/combobox/use-cases.md +377 -0
  48. package/docs/components/dialog/index.md +3 -0
  49. package/docs/components/dialog/overview.md +63 -0
  50. package/docs/components/dialog/src/demo-dialog-style.js +3 -0
  51. package/docs/components/dialog/src/demoStyle.js +39 -0
  52. package/docs/components/dialog/src/slots-dialog-content.js +32 -0
  53. package/docs/components/dialog/src/styled-dialog-content.js +38 -0
  54. package/docs/components/dialog/use-cases.md +154 -0
  55. package/docs/components/drawer/index.md +3 -0
  56. package/docs/components/drawer/overview.md +68 -0
  57. package/docs/components/drawer/src/demoStyle.js +71 -0
  58. package/docs/components/drawer/use-cases.md +194 -0
  59. package/docs/components/fieldset/index.md +3 -0
  60. package/docs/components/fieldset/overview.md +49 -0
  61. package/docs/components/fieldset/use-cases.md +185 -0
  62. package/docs/components/form/index.md +3 -0
  63. package/docs/components/form/overview.md +43 -0
  64. package/docs/components/form/use-cases.md +72 -0
  65. package/docs/components/icon/assets/bugs/bug01.svg.js +2 -0
  66. package/docs/components/icon/assets/bugs/bug02.svg.js +2 -0
  67. package/docs/components/icon/assets/bugs/bug05.svg.js +2 -0
  68. package/docs/components/icon/assets/bugs/bug06.svg.js +2 -0
  69. package/docs/components/icon/assets/bugs/bug08.svg.js +2 -0
  70. package/docs/components/icon/assets/bugs/bug12.svg.js +2 -0
  71. package/docs/components/icon/assets/bugs/bug19.svg.js +2 -0
  72. package/docs/components/icon/assets/bugs/bug23.svg.js +2 -0
  73. package/docs/components/icon/assets/bugs/bug24.svg.js +2 -0
  74. package/docs/components/icon/assets/iconset-bugs.js +11 -0
  75. package/docs/components/icon/assets/iconset-misc.js +3 -0
  76. package/docs/components/icon/assets/iconset-space.js +31 -0
  77. package/docs/components/icon/assets/misc/arrowLeft.svg.js +6 -0
  78. package/docs/components/icon/assets/space/aliens-spaceship.svg.js +2 -0
  79. package/docs/components/icon/assets/space/meteor.svg.js +2 -0
  80. package/docs/components/icon/assets/space/moon-flag.svg.js +2 -0
  81. package/docs/components/icon/assets/space/moon.svg.js +2 -0
  82. package/docs/components/icon/assets/space/night.svg.js +2 -0
  83. package/docs/components/icon/assets/space/orbit.svg.js +2 -0
  84. package/docs/components/icon/assets/space/planet.svg.js +2 -0
  85. package/docs/components/icon/assets/space/robot.svg.js +2 -0
  86. package/docs/components/icon/assets/space/rocket.svg.js +2 -0
  87. package/docs/components/icon/assets/space/satellite.svg.js +2 -0
  88. package/docs/components/icon/assets/space/signal.svg.js +2 -0
  89. package/docs/components/icon/assets/space/space-helmet.svg.js +2 -0
  90. package/docs/components/icon/assets/space/sun.svg.js +2 -0
  91. package/docs/components/icon/assets/space/telescope.svg.js +2 -0
  92. package/docs/components/icon/index.md +3 -0
  93. package/docs/components/icon/overview.md +40 -0
  94. package/docs/components/icon/use-cases.md +93 -0
  95. package/docs/components/index.md +7 -0
  96. package/docs/components/input/index.md +3 -0
  97. package/docs/components/input/overview.md +36 -0
  98. package/docs/components/input/use-cases.md +77 -0
  99. package/docs/components/input-amount/index.md +3 -0
  100. package/docs/components/input-amount/overview.md +49 -0
  101. package/docs/components/input-amount/use-cases.md +122 -0
  102. package/docs/components/input-date/index.md +3 -0
  103. package/docs/components/input-date/overview.md +39 -0
  104. package/docs/components/input-date/use-cases.md +83 -0
  105. package/docs/components/input-datepicker/index.md +3 -0
  106. package/docs/components/input-datepicker/overview.md +42 -0
  107. package/docs/components/input-datepicker/use-cases.md +78 -0
  108. package/docs/components/input-email/index.md +3 -0
  109. package/docs/components/input-email/overview.md +32 -0
  110. package/docs/components/input-email/use-cases.md +48 -0
  111. package/docs/components/input-iban/index.md +3 -0
  112. package/docs/components/input-iban/overview.md +37 -0
  113. package/docs/components/input-iban/use-cases.md +102 -0
  114. package/docs/components/input-range/index.md +3 -0
  115. package/docs/components/input-range/overview.md +34 -0
  116. package/docs/components/input-range/use-cases.md +108 -0
  117. package/docs/components/input-stepper/index.md +3 -0
  118. package/docs/components/input-stepper/overview.md +36 -0
  119. package/docs/components/input-stepper/use-cases.md +41 -0
  120. package/docs/components/input-tel/index.md +3 -0
  121. package/docs/components/input-tel/overview.md +62 -0
  122. package/docs/components/input-tel/src/h-region-code-table.js +109 -0
  123. package/docs/components/input-tel/use-cases.md +307 -0
  124. package/docs/components/input-tel-dropdown/examples.md +32 -0
  125. package/docs/components/input-tel-dropdown/index.md +3 -0
  126. package/docs/components/input-tel-dropdown/overview.md +38 -0
  127. package/docs/components/input-tel-dropdown/src/intl-input-tel-dropdown.js +127 -0
  128. package/docs/components/input-tel-dropdown/use-cases.md +159 -0
  129. package/docs/components/listbox/index.md +3 -0
  130. package/docs/components/listbox/overview.md +42 -0
  131. package/docs/components/listbox/src/listboxData.js +65 -0
  132. package/docs/components/listbox/use-cases.md +147 -0
  133. package/docs/components/pagination/index.md +3 -0
  134. package/docs/components/pagination/overview.md +29 -0
  135. package/docs/components/pagination/use-cases.md +99 -0
  136. package/docs/components/progress-indicator/assets/my-determinate-progress-bar.js +30 -0
  137. package/docs/components/progress-indicator/assets/my-indeterminate-progress-spinner.js +55 -0
  138. package/docs/components/progress-indicator/examples.md +125 -0
  139. package/docs/components/progress-indicator/index.md +3 -0
  140. package/docs/components/progress-indicator/overview.md +36 -0
  141. package/docs/components/radio-group/index.md +3 -0
  142. package/docs/components/radio-group/overview.md +46 -0
  143. package/docs/components/radio-group/use-cases.md +140 -0
  144. package/docs/components/select/index.md +3 -0
  145. package/docs/components/select/overview.md +44 -0
  146. package/docs/components/select/use-cases.md +55 -0
  147. package/docs/components/select-rich/examples.md +31 -0
  148. package/docs/components/select-rich/index.md +3 -0
  149. package/docs/components/select-rich/overview.md +46 -0
  150. package/docs/components/select-rich/src/flagStyles.js +1250 -0
  151. package/docs/components/select-rich/src/flags.png +0 -0
  152. package/docs/components/select-rich/src/flags@2x.png +0 -0
  153. package/docs/components/select-rich/src/intl-select-rich.js +194 -0
  154. package/docs/components/select-rich/src/regionMetaList.js +1717 -0
  155. package/docs/components/select-rich/use-cases.md +370 -0
  156. package/docs/components/steps/index.md +3 -0
  157. package/docs/components/steps/overview.md +63 -0
  158. package/docs/components/steps/use-cases.md +163 -0
  159. package/docs/components/switch/index.md +3 -0
  160. package/docs/components/switch/overview.md +75 -0
  161. package/docs/components/switch/reference.md +39 -0
  162. package/docs/components/switch/use-cases.md +76 -0
  163. package/docs/components/tabs/examples.md +23 -0
  164. package/docs/components/tabs/index.md +3 -0
  165. package/docs/components/tabs/overview.md +48 -0
  166. package/docs/components/tabs/src/lea-tab-panel.js +24 -0
  167. package/docs/components/tabs/src/lea-tab.js +45 -0
  168. package/docs/components/tabs/src/lea-tabs.js +28 -0
  169. package/docs/components/tabs/use-cases.md +219 -0
  170. package/docs/components/textarea/index.md +3 -0
  171. package/docs/components/textarea/overview.md +35 -0
  172. package/docs/components/textarea/use-cases.md +95 -0
  173. package/docs/components/tooltip/examples.md +39 -0
  174. package/docs/components/tooltip/index.md +3 -0
  175. package/docs/components/tooltip/overview.md +44 -0
  176. package/docs/components/tooltip/use-cases.md +208 -0
  177. package/docs/fundamentals/index.md +19 -0
  178. package/docs/fundamentals/node-tools/babel-plugin-extend-docs/index.md +1 -0
  179. package/docs/fundamentals/node-tools/babel-plugin-extend-docs/overview.md +233 -0
  180. package/docs/fundamentals/node-tools/index.md +1 -0
  181. package/docs/fundamentals/node-tools/providence-analytics/LocalConfiguration.md +68 -0
  182. package/docs/fundamentals/node-tools/providence-analytics/QueryResult.md +111 -0
  183. package/docs/fundamentals/node-tools/providence-analytics/analyzer.md +69 -0
  184. package/docs/fundamentals/node-tools/providence-analytics/assets/_mermaid.svg.js +1202 -0
  185. package/docs/fundamentals/node-tools/providence-analytics/dashboard.md +22 -0
  186. package/docs/fundamentals/node-tools/providence-analytics/index.md +1 -0
  187. package/docs/fundamentals/node-tools/providence-analytics/overview.md +192 -0
  188. package/docs/fundamentals/node-tools/publish-docs/index.md +1 -0
  189. package/docs/fundamentals/node-tools/publish-docs/overview.md +136 -0
  190. package/docs/fundamentals/node-tools/remark-extend/index.md +1 -0
  191. package/docs/fundamentals/node-tools/remark-extend/overview.md +274 -0
  192. package/docs/fundamentals/node-tools/rocket-preset-extend-lion-docs/index.md +1 -0
  193. package/docs/fundamentals/node-tools/rocket-preset-extend-lion-docs/overview.md +285 -0
  194. package/docs/fundamentals/rationales/TypeScript.md +18 -0
  195. package/docs/fundamentals/rationales/index.md +1 -0
  196. package/docs/fundamentals/rationales/side-effects.md +203 -0
  197. package/docs/fundamentals/rationales/versioning.md +35 -0
  198. package/docs/fundamentals/systems/core/index.md +3 -0
  199. package/docs/fundamentals/systems/core/overview.md +85 -0
  200. package/docs/fundamentals/systems/form/assets/FormatMixinDiagram-1.svg +1 -0
  201. package/docs/fundamentals/systems/form/assets/FormatMixinDiagram-2.svg +1 -0
  202. package/docs/fundamentals/systems/form/assets/FormatMixinDiagram-3.svg +84 -0
  203. package/docs/fundamentals/systems/form/assets/h-output.js +155 -0
  204. package/docs/fundamentals/systems/form/formatting-and-parsing.md +245 -0
  205. package/docs/fundamentals/systems/form/index.md +3 -0
  206. package/docs/fundamentals/systems/form/interaction-states.md +177 -0
  207. package/docs/fundamentals/systems/form/model-value.md +35 -0
  208. package/docs/fundamentals/systems/form/overview.md +82 -0
  209. package/docs/fundamentals/systems/form/styling.md +101 -0
  210. package/docs/fundamentals/systems/form/use-cases.md +156 -0
  211. package/docs/fundamentals/systems/form/validate.md +929 -0
  212. package/docs/fundamentals/systems/icon/index.md +3 -0
  213. package/docs/fundamentals/systems/icon/overview.md +124 -0
  214. package/docs/fundamentals/systems/index.md +1 -0
  215. package/docs/fundamentals/systems/localize/assets/all-locales.js +437 -0
  216. package/docs/fundamentals/systems/localize/assets/en-AU.js +6 -0
  217. package/docs/fundamentals/systems/localize/assets/en-GB.js +6 -0
  218. package/docs/fundamentals/systems/localize/assets/en-US.js +6 -0
  219. package/docs/fundamentals/systems/localize/assets/en.js +4 -0
  220. package/docs/fundamentals/systems/localize/assets/nl-BE.js +6 -0
  221. package/docs/fundamentals/systems/localize/assets/nl-NL.js +6 -0
  222. package/docs/fundamentals/systems/localize/assets/nl.js +4 -0
  223. package/docs/fundamentals/systems/localize/dates.md +195 -0
  224. package/docs/fundamentals/systems/localize/index.md +3 -0
  225. package/docs/fundamentals/systems/localize/numbers.md +217 -0
  226. package/docs/fundamentals/systems/localize/overview.md +48 -0
  227. package/docs/fundamentals/systems/localize/rationale.md +62 -0
  228. package/docs/fundamentals/systems/localize/text.md +125 -0
  229. package/docs/fundamentals/systems/localize/use-cases.md +319 -0
  230. package/docs/fundamentals/systems/overlays/assets/applyDemoOverlayStyles.js +22 -0
  231. package/docs/fundamentals/systems/overlays/assets/demo-overlay-backdrop.js +48 -0
  232. package/docs/fundamentals/systems/overlays/assets/demo-overlay-system.js +42 -0
  233. package/docs/fundamentals/systems/overlays/assets/umbrella-form.js +133 -0
  234. package/docs/fundamentals/systems/overlays/configuration.md +453 -0
  235. package/docs/fundamentals/systems/overlays/form-integration.md +65 -0
  236. package/docs/fundamentals/systems/overlays/index.md +3 -0
  237. package/docs/fundamentals/systems/overlays/overview.md +118 -0
  238. package/docs/fundamentals/systems/overlays/rationale.md +232 -0
  239. package/docs/fundamentals/systems/overlays/scope.md +176 -0
  240. package/docs/fundamentals/systems/overlays/use-cases.md +699 -0
  241. package/docs/fundamentals/tools/ajax/assets/naga.json +9 -0
  242. package/docs/fundamentals/tools/ajax/assets/pabu.json +9 -0
  243. package/docs/fundamentals/tools/ajax/index.md +3 -0
  244. package/docs/fundamentals/tools/ajax/overview.md +128 -0
  245. package/docs/fundamentals/tools/ajax/use-cases.md +456 -0
  246. package/docs/fundamentals/tools/helpers/action-logger.md +165 -0
  247. package/docs/fundamentals/tools/helpers/index.md +3 -0
  248. package/docs/fundamentals/tools/helpers/overview.md +30 -0
  249. package/docs/fundamentals/tools/index.md +1 -0
  250. package/docs/fundamentals/tools/singleton-manager/index.md +3 -0
  251. package/docs/fundamentals/tools/singleton-manager/overview.md +304 -0
  252. package/docs/guides/how-to/create-a-custom-field.md +200 -0
  253. package/docs/guides/how-to/extend-a-native-input.md +66 -0
  254. package/docs/guides/how-to/get-started.md +77 -0
  255. package/docs/guides/how-to/index.md +1 -0
  256. package/docs/guides/index.md +34 -0
  257. package/docs/guides/principles/definitions-and-terms.md +41 -0
  258. package/docs/guides/principles/index.md +26 -0
  259. package/docs/guides/principles/scoped-elements.md +103 -0
  260. package/docs/guides/principles/styling.md +32 -0
  261. package/docs/guides/principles/subclasser-apis.md +28 -0
  262. package/docs/override.js +15 -0
  263. package/package.json +1 -1
@@ -0,0 +1,929 @@
1
+ # Systems >> Form >> Validate ||30
2
+
3
+ ```js script
4
+ import { html } from '@mdjs/mdjs-preview';
5
+ import { LionInput } from '@lion/ui/input.js';
6
+ import '@lion/ui/define/lion-checkbox-group.js';
7
+ import '@lion/ui/define/lion-checkbox-group.js';
8
+ import '@lion/ui/define/lion-combobox.js';
9
+ import '@lion/ui/define/lion-fieldset.js';
10
+ import '@lion/ui/define/lion-form.js';
11
+ import '@lion/ui/define/lion-input-amount.js';
12
+ import '@lion/ui/define/lion-input-date.js';
13
+ import '@lion/ui/define/lion-input-datepicker.js';
14
+ import '@lion/ui/define/lion-input-email.js';
15
+ import '@lion/ui/define/lion-input-iban.js';
16
+ import '@lion/ui/define/lion-input-range.js';
17
+ import '@lion/ui/define/lion-input-stepper.js';
18
+ import '@lion/ui/define/lion-input.js';
19
+ import '@lion/ui/define/lion-listbox.js';
20
+ import '@lion/ui/define/lion-listbox.js';
21
+ import '@lion/ui/define/lion-option.js';
22
+ import '@lion/ui/define/lion-options.js';
23
+ import '@lion/ui/define/lion-radio-group.js';
24
+ import '@lion/ui/define/lion-radio-group.js';
25
+ import '@lion/ui/define/lion-radio.js';
26
+ import '@lion/ui/define/lion-select.js';
27
+ import '@lion/ui/define/lion-select-rich.js';
28
+ import '@lion/ui/define/lion-textarea.js';
29
+ import {
30
+ DefaultSuccess,
31
+ EqualsLength,
32
+ IsDate,
33
+ IsEmail,
34
+ IsNumber,
35
+ IsString,
36
+ MaxDate,
37
+ MaxLength,
38
+ MaxNumber,
39
+ MinDate,
40
+ MinLength,
41
+ MinMaxDate,
42
+ MinMaxLength,
43
+ MinMaxNumber,
44
+ MinNumber,
45
+ Required,
46
+ Validator,
47
+ Pattern,
48
+ Unparseable,
49
+ } from '@lion/ui/form-core.js';
50
+ import { localize } from '@lion/ui/localize.js';
51
+ import { loadDefaultFeedbackMessages } from '@lion/ui/validate-messages.js';
52
+ import { renderLitAsNode } from '@lion/ui/helpers.js';
53
+ ```
54
+
55
+ ## When validation happens
56
+
57
+ Validation happens on every change of `modelValue`. A change in modelValue can be originated from either user interaction or an imperative action from an Application Developer. We could therefore say validation happens 'realtime'. This is aligned with the platform.
58
+
59
+ ## When validation feedback will be shown
60
+
61
+ Although validation happens realtime under the hood, displaying validity feedback in realtime may not always lead to the desired User Experience. Together with [interaction states](https://github.com/ing-bank/lion/blob/fbf0bd22378e76aa4261c2a97faf8be4f5fc461e/docs/fundamentals/systems/form/interaction-states.md),
62
+ validity states can determine whether a validation message should be shown along the input field.
63
+
64
+ ## Assessing field validation state programmatically
65
+
66
+ When a field has validation feedback it can be accessed using the `hasFeedbackFor` and `showsFeedbackFor` properties. This can be used if the validity of the field is needed in code.
67
+
68
+ - `hasFeedbackFor` is the state of the field regardless of whether the feedback is shown or not.
69
+ - `showsFeedbackFor` represents whether or not validation feedback is being shown. This takes into account interaction state such as a field being `touched` and `dirty`, `prefilled` or `submitted`
70
+
71
+ ```js
72
+ // Field is invalid and has not interacted with
73
+ const field = document.querySelector('#my-field');
74
+ field.hasFeedbackFor.includes('error'); // returns true
75
+ field.showsFeedbackFor.includes('error'); // returns false
76
+
77
+ // Field invalid, dirty and touched
78
+ field.hasFeedbackFor.includes('error'); // returns true
79
+ field.showsFeedbackFor.includes('error'); // returns true
80
+ ```
81
+
82
+ ## Features
83
+
84
+ - Allow for advanced UX scenarios by updating validation state on every value change
85
+ - Provide a powerful way of writing validation via pure functions
86
+ - Default validators
87
+ - Custom validators
88
+ - Multiple validation types(error, warning, info, success)
89
+
90
+ Our validation system is designed to:
91
+
92
+ - Allow for advanced UX scenarios by updating validation state on every value change
93
+ - Provide a powerful way of writing validations via classes.
94
+
95
+ ## Validators
96
+
97
+ All validators are extensions of the `Validator` class. They should be applied to the element implementing `ValidateMixin` as follows:
98
+
99
+ ```html
100
+ <validatable-el
101
+ .validators="${[new MyValidator({ myParam: 'foo' }), { extra: 'options' } ]]}"
102
+ ></validatable-el>
103
+ ```
104
+
105
+ As you can see the 'validators' property expects a map (an array of arrays). So, every Validator is a class consisting of:
106
+
107
+ - validator function
108
+ - validator parameters (optional)
109
+ - validator config (optional)
110
+
111
+ ### Validator classes
112
+
113
+ All validators extend from the default `Validator` class. Below is an example of what a validator could look like:
114
+
115
+ ```js
116
+ class EqualsText extends Validator {
117
+ static validatorName = 'EqualsText';
118
+
119
+ /**
120
+ * Returns true when 'activated' (c.q. in error/warning/info state)
121
+ * @param {string} modelValue
122
+ */
123
+ execute(modelValue, param) {
124
+ return modelValue !== param;
125
+ }
126
+
127
+ static getMessage({ fieldName, modelValue, formControl }) {
128
+ return `Please make sure values are equal`;
129
+ }
130
+ }
131
+ ```
132
+
133
+ The `execute()` method returns a boolean by default, but it can also be customized to return enums instead. In this example below, we customize the method to return one among some possible enums as strings.
134
+
135
+ ```js
136
+ class EnumOutComeValidator extends Validator {
137
+ static validatorName = 'EnumOutCome';
138
+
139
+ /**
140
+ * @param {string} modelValue
141
+ * @param {number} maxLength
142
+ * @returns {false|'overload'|'error'}
143
+ */
144
+ execute(modelValue, maxLength) {
145
+ if (modelValue.length > maxLength) {
146
+ return 'overload';
147
+ } else if (modelValue.length < 0) {
148
+ return 'error';
149
+ }
150
+ return false;
151
+ }
152
+
153
+ /**
154
+ * @param {{outcome: 'overload'|'error'|false}} opts
155
+ */
156
+ static async getMessage({ outcome }) {
157
+ const results = {
158
+ overload: 'Too many characters!',
159
+ error: 'Something went wrong..',
160
+ false: 'All good!',
161
+ };
162
+ return results[outcome];
163
+ }
164
+ }
165
+ ```
166
+
167
+ ```html
168
+ <validatable-el .validators="${[new EqualsText('foo')]}"></validatable-el>
169
+ ```
170
+
171
+ ## Installation
172
+
173
+ ```bash
174
+ npm i --save @lion/ui
175
+ ```
176
+
177
+ ```js
178
+ import '@lion/ui/define/lion-input.js';
179
+ import { %ValidatorName% } from '@lion/ui/form-core.js';
180
+ ```
181
+
182
+ ## Default Validators
183
+
184
+ By default, the validate system ships with the following validators:
185
+
186
+ - **Required**
187
+ - **String Validators**, IsString, EqualsLength, MinLength, MaxLength, MinMaxLength, Pattern
188
+ - **Number Validators**, IsNumber, MinNumber, MaxNumber, MinMaxNumber
189
+ - **Date Validators**, IsDate, MinDate, MaxDate, MinMaxDate, IsDateDisabled
190
+ - **Email Validator**, IsEmail
191
+
192
+ All validators return `false` if the required validity state is met.
193
+
194
+ All validators are considered self explanatory due to their explicit namings.
195
+
196
+ ```bash
197
+ npm i --save @lion/ui
198
+ ```
199
+
200
+ ```js
201
+ import { loadDefaultFeedbackMessages } from '@lion/ui/validate-messages.js';
202
+ ```
203
+
204
+ ```js preview-story
205
+ export const defaultValidationMessages = () => {
206
+ loadDefaultFeedbackMessages();
207
+ return html`
208
+ <lion-input
209
+ name="value"
210
+ label="Default validation"
211
+ .fieldName="${'value'}"
212
+ .validators="${[new Required(), new MinLength(4)]}"
213
+ .modelValue="${'foo'}"
214
+ ></lion-input>
215
+ <button @click=${() => (localize.locale = 'de-DE')}>DE</button>
216
+ <button @click=${() => (localize.locale = 'en-GB')}>EN</button>
217
+ <button @click=${() => (localize.locale = 'fr-FR')}>FR</button>
218
+ <button @click=${() => (localize.locale = 'nl-NL')}>NL</button>
219
+ <button @click=${() => (localize.locale = 'zh-CN')}>CN</button>
220
+ `;
221
+ };
222
+ ```
223
+
224
+ Once the method `loadDefaultFeedbackMessages` is called, it will make sure that all validators provided in `@lion/form-core` will have a default error message. It uses the `@lion/localize` system to provide these translations and has support for more than 15 locales.
225
+
226
+ ### Required
227
+
228
+ The required validator can be put onto every form field element and will make sure that element is not empty. For an input that may mean that it is not an empty string, while for a `checkbox-group` it means at least one `checkbox` needs to be checked.
229
+
230
+ ```js preview-story
231
+ export const requiredValidator = () => html`
232
+ <lion-input .validators=${[new Required()]} label="Required"></lion-input>
233
+ `;
234
+ ```
235
+
236
+ ### String Validators
237
+
238
+ Useful on input elements it allows to define how many characters can be entered.
239
+
240
+ ```js preview-story
241
+ export const stringValidators = () => html`
242
+ <lion-input
243
+ .validators=${[new EqualsLength(7)]}
244
+ .modelValue=${'not exactly'}
245
+ label="EqualsLength"
246
+ ></lion-input>
247
+ <lion-input
248
+ .validators=${[new MinLength(10)]}
249
+ .modelValue=${'too short'}
250
+ label="MinLength"
251
+ ></lion-input>
252
+ <lion-input
253
+ .validators=${[new MaxLength(7)]}
254
+ .modelValue=${'too long'}
255
+ label="MaxLength"
256
+ ></lion-input>
257
+ <lion-input
258
+ .validators=${[new MinMaxLength({ min: 10, max: 20 })]}
259
+ .modelValue=${'that should be enough'}
260
+ label="MinMaxLength"
261
+ ></lion-input>
262
+ <lion-input
263
+ .validators=${[new Pattern(/#LionRocks/)]}
264
+ .modelValue=${'regex checks if "#Lion<NO SPACE>Rocks" is in this input #LionRocks'}
265
+ label="Pattern"
266
+ ></lion-input>
267
+ `;
268
+ ```
269
+
270
+ ### Number Validators
271
+
272
+ Number validations assume that it's modelValue is actually a number.
273
+ Therefore it may only be used on input that have an appropriate parser/formatter like the `input-amount`.
274
+
275
+ ```js preview-story
276
+ export const numberValidators = () => html`
277
+ <lion-input-amount
278
+ .validators="${[new IsNumber()]}"
279
+ .modelValue="${'foo'}"
280
+ label="IsNumber"
281
+ ></lion-input-amount>
282
+ <lion-input-amount
283
+ .validators="${[new MinNumber(7)]}"
284
+ .modelValue="${5}"
285
+ label="MinNumber"
286
+ ></lion-input-amount>
287
+ <lion-input-amount
288
+ .validators="${[new MaxNumber(7)]}"
289
+ .modelValue="${9}"
290
+ label="MaxNumber"
291
+ ></lion-input-amount>
292
+ <lion-input-amount
293
+ .validators="${[new MinMaxNumber({ min: 10, max: 20 })]}"
294
+ .modelValue="${5}"
295
+ label="MinMaxNumber"
296
+ ></lion-input-amount>
297
+ `;
298
+ ```
299
+
300
+ ### Date Validators
301
+
302
+ Date validators work with real javascript dates. Use them on `input-date` or `input-datepicker`.
303
+
304
+ ```js preview-story
305
+ export const dateValidators = () => {
306
+ const today = new Date();
307
+ const year = today.getFullYear();
308
+ const month = today.getMonth();
309
+ const day = today.getDate();
310
+ const yesterday = new Date(year, month, day - 1);
311
+ const tomorrow = new Date(year, month, day + 1);
312
+ return html`
313
+ <lion-input-date
314
+ .validators=${[new IsDate()]}
315
+ .modelValue=${'foo'}
316
+ label="IsDate"
317
+ ></lion-input-date>
318
+ <lion-input-date
319
+ .validators=${[new MinDate(today)]}
320
+ .modelValue=${new Date(yesterday)}
321
+ label="MinDate"
322
+ ></lion-input-date>
323
+ <lion-input-date
324
+ .validators=${[new MaxDate(today)]}
325
+ .modelValue=${new Date(tomorrow)}
326
+ label="MaxDate"
327
+ ></lion-input-date>
328
+ <lion-input-date
329
+ .validators=${[new MinMaxDate({ min: new Date(yesterday), max: new Date(tomorrow) })]}
330
+ .modelValue=${new Date(today)}
331
+ label="MinMaxDate"
332
+ ></lion-input-date>
333
+ `;
334
+ };
335
+ ```
336
+
337
+ ### Email Validator
338
+
339
+ ```js preview-story
340
+ export const emailValidator = () => html`
341
+ <lion-input-email
342
+ .validators="${[new IsEmail()]}"
343
+ .modelValue="${'foo'}"
344
+ label="IsEmail"
345
+ ></lion-input-email>
346
+ `;
347
+ ```
348
+
349
+ ### Override Default Messages
350
+
351
+ To get default validation messages you need to import and call the `loadDefaultFeedbackMessages` function once in your application.
352
+
353
+ Sometimes the default messages don't make sense for your input field. In that case you want to override it by adding a `getMessage` function to your validator.
354
+
355
+ ```js preview-story
356
+ export const defaultMessages = () => html`
357
+ <lion-input
358
+ .validators="${[new EqualsLength(4, { getMessage: () => '4 chars please...' })]}"
359
+ .modelValue="${'123'}"
360
+ label="Custom message for validator instance"
361
+ ></lion-input>
362
+ <lion-input
363
+ .validators="${[
364
+ new EqualsLength(4, {
365
+ getMessage: ({ modelValue, params: param }) => {
366
+ const diff = modelValue.length - param;
367
+ return `${Math.abs(diff)} too ${diff > 0 ? 'much' : 'few'}...`;
368
+ },
369
+ }),
370
+ ]}"
371
+ .modelValue="${'way too much'}"
372
+ label="Dynamic message for validator instance"
373
+ ></lion-input>
374
+ `;
375
+ ```
376
+
377
+ ### Override fieldName
378
+
379
+ In the scenario that the default messages are correct, but you only want to change the `fieldName`, this can both be done for a single specific validator or for all at once.
380
+
381
+ ```js preview-story
382
+ export const overrideFieldName = () => html`
383
+ <lion-input
384
+ .validators="${[new EqualsLength(4, { fieldName: 'custom fieldName' })]}"
385
+ .modelValue="${'123'}"
386
+ label="Custom fieldName for 1 validator"
387
+ ></lion-input>
388
+ <lion-input
389
+ .validators="${[new Required(), new EqualsLength(4)]}"
390
+ .fieldName="${'custom fieldName'}"
391
+ .modelValue="${'123'}"
392
+ label="Custom fieldName for all validators"
393
+ ></lion-input>
394
+ `;
395
+ ```
396
+
397
+ ## Custom Validators
398
+
399
+ Here is an example how you can make your own validator and providing the error messages directly within. You can even hard code localization in there if needed or you can use a localization system.
400
+
401
+ > Note that we import an `lion-input` here as an example of a form control implementing `ValidateMixin`.
402
+ > We could equally well use `lion-textarea`, `lion-select`, `lion-fieldset` etc. to illustrate our example.
403
+
404
+ ```js preview-story
405
+ export const customValidators = () => {
406
+ const isInitialsRegex = /^([A-Z]\.)+$/;
407
+ class IsInitialsExample extends Validator {
408
+ static get validatorName() {
409
+ return 'IsExampleInitials';
410
+ }
411
+
412
+ execute(value) {
413
+ let hasFeedback = false;
414
+ const isStringValidator = new IsString();
415
+ if (isStringValidator.execute(value) || !isInitialsRegex.test(value)) {
416
+ hasFeedback = true;
417
+ }
418
+ return hasFeedback;
419
+ }
420
+
421
+ static getMessage({ fieldName }) {
422
+ return `Please enter a valid ${fieldName} in the format "L.I.".`;
423
+ }
424
+ }
425
+ return html`
426
+ <lion-input
427
+ label="Initials"
428
+ name="initials"
429
+ .validators="${[new IsInitialsExample('mine')]}"
430
+ ></lion-input>
431
+ `;
432
+ };
433
+ ```
434
+
435
+ The custom `IsInitialsExample` checks if the value is fitting our regex, but does not prevent the user from submitting other values.
436
+
437
+ Retrieving validity states is as easy as checking for:
438
+
439
+ ```js
440
+ myInitialsInput.hasFeedbackFor.include('error');
441
+ ```
442
+
443
+ ## Validation Examples
444
+
445
+ ### Checkbox Validator
446
+
447
+ You can apply validation to the `<lion-checkbox-group>`, similar to how you would do so in any fieldset. The interaction states of the `<lion-checkbox-group>` are evaluated in order to hide or show feedback messages.
448
+
449
+ ```js preview-story
450
+ export const checkboxValidation = () => {
451
+ const validate = e => {
452
+ const checkboxGroup = e.target.parentElement.querySelector('#scientists');
453
+ checkboxGroup.submitted = !checkboxGroup.submitted;
454
+ };
455
+ return html`
456
+ <lion-checkbox-group
457
+ id="scientists"
458
+ name="scientists[]"
459
+ label="Favorite scientists"
460
+ .validators=${[new Required()]}
461
+ >
462
+ <lion-checkbox label="Archimedes" .choiceValue=${'Archimedes'}></lion-checkbox>
463
+ <lion-checkbox label="Francis Bacon" .choiceValue=${'Francis Bacon'}></lion-checkbox>
464
+ <lion-checkbox label="Marie Curie" .choiceValue=${'Marie Curie'}></lion-checkbox>
465
+ </lion-checkbox-group>
466
+ <button @click="${e => validate(e)}">Validate</button>
467
+ `;
468
+ };
469
+ ```
470
+
471
+ Below is a more advanced validator on the group that evaluates the children checkboxes' checked states.
472
+
473
+ ```js preview-story
474
+ export const checkboxValidationAdvanced = () => {
475
+ class HasMinTwoChecked extends Validator {
476
+ execute(value) {
477
+ return value.length < 2;
478
+ }
479
+ static get validatorName() {
480
+ return 'HasMinTwoChecked';
481
+ }
482
+ static async getMessage() {
483
+ return 'You need to select at least 2 values.';
484
+ }
485
+ }
486
+ const validate = e => {
487
+ const checkboxGroup = e.target.parentElement.querySelector('#scientists2');
488
+ checkboxGroup.submitted = !checkboxGroup.submitted;
489
+ };
490
+ return html`
491
+ <lion-checkbox-group
492
+ id="scientists2"
493
+ name="scientists2[]"
494
+ label="Favorite scientists"
495
+ help-text="You should have at least 2 of those"
496
+ .validators=${[new Required(), new HasMinTwoChecked()]}
497
+ >
498
+ <lion-checkbox label="Archimedes" .choiceValue=${'Archimedes'}></lion-checkbox>
499
+ <lion-checkbox label="Francis Bacon" .choiceValue=${'Francis Bacon'}></lion-checkbox>
500
+ <lion-checkbox label="Marie Curie" .choiceValue=${'Marie Curie'}></lion-checkbox>
501
+ </lion-checkbox-group>
502
+ <button @click="${e => validate(e)}">Validate</button>
503
+ `;
504
+ };
505
+ ```
506
+
507
+ ### Radio Validator
508
+
509
+ ```js preview-story
510
+ export const radioValidation = () => {
511
+ const validate = e => {
512
+ const radioGroup = e.target.parentElement.querySelector('#dinos1');
513
+ radioGroup.submitted = !radioGroup.submitted;
514
+ };
515
+ return html`
516
+ <lion-radio-group
517
+ id="dinos1"
518
+ name="dinos1"
519
+ label="Favourite dinosaur"
520
+ .validators=${[new Required()]}
521
+ >
522
+ <lion-radio label="allosaurus" .choiceValue=${'allosaurus'}></lion-radio>
523
+ <lion-radio label="brontosaurus" .choiceValue=${'brontosaurus'}></lion-radio>
524
+ <lion-radio label="diplodocus" .choiceValue="${'diplodocus'}"></lion-radio>
525
+ </lion-radio-group>
526
+ <button @click="${e => validate(e)}">Validate</button>
527
+ `;
528
+ };
529
+ ```
530
+
531
+ You can also create a validator that validates whether a certain option is checked.
532
+
533
+ ```js preview-story
534
+ export const radioValidationAdvanced = () => {
535
+ class IsBrontosaurus extends Validator {
536
+ static get validatorName() {
537
+ return 'IsBrontosaurus';
538
+ }
539
+ execute(value) {
540
+ let showFeedback = false;
541
+ if (value !== 'brontosaurus') {
542
+ showFeedback = true;
543
+ }
544
+ return showFeedback;
545
+ }
546
+ static async getMessage() {
547
+ return 'You need to select "brontosaurus"';
548
+ }
549
+ }
550
+ const validate = e => {
551
+ const radioGroup = e.target.parentElement.querySelector('#dinos2');
552
+ radioGroup.submitted = !radioGroup.submitted;
553
+ };
554
+ return html`
555
+ <lion-radio-group
556
+ id="dinos2"
557
+ name="dinos2"
558
+ label="Favourite dinosaur"
559
+ .validators=${[new Required(), new IsBrontosaurus()]}
560
+ >
561
+ <lion-radio label="allosaurus" .choiceValue=${'allosaurus'}></lion-radio>
562
+ <lion-radio label="brontosaurus" .choiceValue=${'brontosaurus'}></lion-radio>
563
+ <lion-radio label="diplodocus" .choiceValue=${'diplodocus'}></lion-radio>
564
+ </lion-radio-group>
565
+ <button @click="${e => validate(e)}">Validate</button>
566
+ `;
567
+ };
568
+ ```
569
+
570
+ ### Combobox
571
+
572
+ Validation can be used as normal, below is an example of a combobox with a `Required` validator.
573
+
574
+ ```js preview-story
575
+ export const validationCombobox = () => html`
576
+ <lion-combobox .validators="${[new Required()]}" name="favoriteMovie" label="Favorite movie">
577
+ <lion-option checked .choiceValue=${'Rocky'}>Rocky</lion-option>
578
+ <lion-option .choiceValue=${'Rocky II'}>Rocky II</lion-option>
579
+ <lion-option .choiceValue=${'Rocky III'}>Rocky III</lion-option>
580
+ <lion-option .choiceValue=${'Rocky IV'}>Rocky IV</lion-option>
581
+ <lion-option .choiceValue=${'Rocky V'}>Rocky V</lion-option>
582
+ <lion-option .choiceValue=${'Rocky Balboa'}>Rocky Balboa</lion-option>
583
+ </lion-combobox>
584
+ `;
585
+ ```
586
+
587
+ ## Validation Types
588
+
589
+ The most common use case for validation is the assessment of whether the input is in error state. An error state would be considered blocking: it prevents a form from being submitted to the server.
590
+
591
+ However, the validation system also supports three non blocking validation feedback types. Summed up, we have the following four types:
592
+
593
+ - **error**: blocking the field from being submitted to the server. For example:
594
+ "Please enter an amount higher than 1000,00 euro."
595
+ - **warning**: something looks wrong, but it is not blocking. For example an optional email input:
596
+ "Please enter a valid e-mail address in the format "name@example.com"."
597
+ - **info**: shows extra information. For example a message of a scheduled payment planner:
598
+ "Ends on 15/05/2020 after 5 payments."
599
+ - **success**: will only be triggered if there was a Message from one of the above validation types and is now correct. For example: "Ok, correct."
600
+
601
+ The api for warning validators and info validators are as follows:
602
+
603
+ ```js preview-story
604
+ export const validationTypes = () => {
605
+ try {
606
+ class MyTypesInput extends LionInput {
607
+ static get validationTypes() {
608
+ return ['error', 'warning', 'info', 'success'];
609
+ }
610
+ }
611
+ customElements.define('my-types-input', MyTypesInput);
612
+ } catch (err) {
613
+ // expected as it is a demo
614
+ }
615
+ return html`
616
+ <style>
617
+ .demo-types-input {
618
+ padding: 0.5rem;
619
+ }
620
+ .demo-types-input[shows-feedback-for~='success'] {
621
+ background-color: #e4ffe4;
622
+ border: 1px solid green;
623
+ }
624
+ .demo-types-input[shows-feedback-for~='error'] {
625
+ background-color: #ffd4d4;
626
+ border: 1px solid red;
627
+ }
628
+ .demo-types-input[shows-feedback-for~='warning'] {
629
+ background-color: #ffe4d4;
630
+ border: 1px solid orange;
631
+ }
632
+ .demo-types-input[shows-feedback-for~='info'] {
633
+ background-color: #d4e4ff;
634
+ border: 1px solid blue;
635
+ }
636
+ </style>
637
+ <my-types-input
638
+ .validators="${[
639
+ new Required(),
640
+ new MinLength(7, { type: 'warning' }),
641
+ new MaxLength(10, {
642
+ type: 'info',
643
+ getMessage: () => `Please, keep the length below the 10 characters.`,
644
+ }),
645
+ new DefaultSuccess(),
646
+ ]}"
647
+ .modelValue="${'exactly'}"
648
+ label="Validation Types"
649
+ class="demo-types-input"
650
+ ></my-types-input>
651
+ `;
652
+ };
653
+ ```
654
+
655
+ Success validators work a bit differently. Their success state is defined by the lack of a previously existing erroneous state (which can be an error or warning state).
656
+
657
+ So, an error validator going from invalid (true) state to invalid(false) state, will trigger the success validator.
658
+
659
+ ## Asynchronous validation
660
+
661
+ By default, all validations are run synchronously. However, for instance when validation can only take place on server level, asynchronous validation will be needed.
662
+
663
+ You can make your async validators as follows:
664
+
665
+ ```js preview-story
666
+ export const asynchronousValidation = () => {
667
+ function pause(ms = 0) {
668
+ return new Promise(resolve => {
669
+ setTimeout(() => {
670
+ resolve();
671
+ }, ms);
672
+ });
673
+ }
674
+ class AsyncValidator extends Validator {
675
+ constructor(...args) {
676
+ super(...args);
677
+ }
678
+ static get validatorName() {
679
+ return 'asyncValidator';
680
+ }
681
+ static get async() {
682
+ return true;
683
+ }
684
+ async execute() {
685
+ console.log('async pending...');
686
+ await pause(2000);
687
+ console.log('async done...');
688
+ return true;
689
+ }
690
+ static getMessage({ modelValue }) {
691
+ return `validated for modelValue: ${modelValue}...`;
692
+ }
693
+ }
694
+ return html`
695
+ <style>
696
+ lion-input[is-pending] {
697
+ opacity: 0.5;
698
+ }
699
+ </style>
700
+ <lion-input
701
+ label="Async validation"
702
+ .validators="${[new AsyncValidator()]}"
703
+ .modelValue="${'123'}"
704
+ ></lion-input>
705
+ `;
706
+ };
707
+ ```
708
+
709
+ ## Dynamic parameter change
710
+
711
+ ```js preview-story
712
+ export const dynamicParameterChange = () => {
713
+ const beginDate = new Date('09/09/1990');
714
+ const minDateValidatorRef = new MinDate(beginDate, {
715
+ message: 'Fill in a date after your birth date',
716
+ });
717
+ return html`
718
+ <lion-input-date
719
+ label="Birth date"
720
+ help-text="Adjust this date to retrigger validation of the input below..."
721
+ .modelValue="${beginDate}"
722
+ @model-value-changed="${({ target: { modelValue, errorState } }) => {
723
+ if (!errorState) {
724
+ // Since graduation date is usually not before birth date
725
+ minDateValidatorRef.param = modelValue;
726
+ }
727
+ }}"
728
+ ></lion-input-date>
729
+ <lion-input-date
730
+ label="Graduation date"
731
+ .modelValue="${new Date('09/09/1989')}"
732
+ .validators="${[minDateValidatorRef]}"
733
+ ></lion-input-date>
734
+ `;
735
+ };
736
+ ```
737
+
738
+ ## Disabled inputs validation
739
+
740
+ According to the W3C specs, Disabled fields should not be validated. Therefore if the attribute disabled is present on a `lion-input` it will not be validated.
741
+
742
+ ```js preview-story
743
+ export const disabledInputsValidation = () => html`
744
+ <lion-input
745
+ disabled
746
+ .validators=${[new EqualsLength(7)]}
747
+ .modelValue=${'not exactly'}
748
+ label="EqualsLength"
749
+ ></lion-input>
750
+ `;
751
+ ```
752
+
753
+ ## Backend validation
754
+
755
+ Backend validation is needed in some cases. For example, you have a sign up form, the username could be already taken. You can add an `AsyncValidator` to check the availability when the `username` field is changed but you may have a conflict when you submit the form (another user take the username in parallel).
756
+
757
+ ```js preview-story
758
+ export const backendValidation = () => {
759
+ // Mock
760
+ function fakeFetch(ms = 0, withError = false) {
761
+ return new Promise(resolve => {
762
+ setTimeout(() => {
763
+ resolve(
764
+ new Response(
765
+ JSON.stringify({
766
+ message: withError ? 'Username is already taken' : '',
767
+ }),
768
+ { status: withError ? 400 : 200 },
769
+ ),
770
+ );
771
+ }, ms);
772
+ });
773
+ }
774
+
775
+ let backendValidationResolver;
776
+ let backendErrorMessage = 'Unknown Error';
777
+ let isBackendCallPending = false;
778
+
779
+ const submitHandler = ev => {
780
+ const lionForm = ev.target;
781
+ if (lionForm.hasFeedbackFor.includes('error')) {
782
+ const firstFormElWithError = lionForm.formElements.find(el =>
783
+ el.hasFeedbackFor.includes('error'),
784
+ );
785
+ firstFormElWithError.focus();
786
+ return;
787
+ }
788
+ isBackendCallPending = true;
789
+ lionForm.formElements.username.validate(); // => backendValidationResolver will be assigned
790
+ const formData = lionForm.serializedValue;
791
+ fakeFetch(2000, formData.simulateError.length).then(async response => {
792
+ if (response.status !== 200) {
793
+ backendErrorMessage = (await response.json())?.message;
794
+ backendValidationResolver(true);
795
+ }
796
+ backendValidationResolver(false);
797
+ isBackendCallPending = false;
798
+ });
799
+ };
800
+
801
+ class BackendValidator extends Validator {
802
+ static get validatorName() {
803
+ return 'backendValidator';
804
+ }
805
+ static get async() {
806
+ return true;
807
+ }
808
+ async execute() {
809
+ if (isBackendCallPending) {
810
+ return await new Promise(resolve => (backendValidationResolver = resolve));
811
+ }
812
+ return false;
813
+ }
814
+ static getMessage({ fieldName, modelValue, params: param }) {
815
+ return backendErrorMessage;
816
+ }
817
+ }
818
+ return html`
819
+ <style>
820
+ lion-input[is-pending] {
821
+ opacity: 0.5;
822
+ }
823
+ </style>
824
+ <lion-form @submit=${submitHandler}>
825
+ <form>
826
+ <lion-input
827
+ label="username"
828
+ name="username"
829
+ .validators="${[new BackendValidator(''), new Required()]}"
830
+ .modelValue="${''}"
831
+ ></lion-input>
832
+ <lion-checkbox-group name="simulateError">
833
+ <lion-checkbox label="Check to simulate a backend error"></lion-checkbox>
834
+ </lion-checkbox-group>
835
+ <lion-button-submit>Submit</lion-button-submit>
836
+ </form>
837
+ </lion-form>
838
+ `;
839
+ };
840
+ ```
841
+
842
+ ## Multiple field validation
843
+
844
+ When validation is dependent on muliple fields, two approaches can be considered:
845
+
846
+ - Fieldset validation
847
+ - Validators with knowledge about context
848
+
849
+ ### Fieldset validation
850
+
851
+ Assume we have a field `startDate` and `endDate` field, with condition `startDate` < `endDate`.
852
+ The easiest way to achieve this, is by adding a Validator to a fieldset wrapping those fields.
853
+
854
+ ```js preview-story
855
+ const isInterpretable = mv => mv && !(mv instanceof Unparseable);
856
+
857
+ class Interval extends Validator {
858
+ static get validatorName() {
859
+ return 'Interval';
860
+ }
861
+
862
+ execute({ startDate, endDate }) {
863
+ if (isInterpretable(startDate) && isInterpretable(endDate)) {
864
+ return !(startDate < endDate);
865
+ }
866
+ return false;
867
+ }
868
+
869
+ static async getMessage() {
870
+ return `The start date should be before the end date`;
871
+ }
872
+ }
873
+ export const fieldsetValidation = () => html`
874
+ <lion-fieldset .validators="${[new Interval()]}">
875
+ <lion-input-date name="startDate" label="Start date"></lion-input-date>
876
+ <lion-input-date name="endDate" label="End date"></lion-input-date>
877
+ </lion-fieldset>
878
+ `;
879
+ ```
880
+
881
+ ### Validators with knowledge about context
882
+
883
+ Assume we want to create password validation with a confirmation field.
884
+ We don't want to show feedback on group level, but right beneath the fields.
885
+
886
+ ```js preview-story
887
+ const isInterpretableValue = mv => mv && !(mv instanceof Unparseable);
888
+
889
+ class PasswordMatch extends Validator {
890
+ static get validatorName() {
891
+ return 'PasswordsMatch';
892
+ }
893
+
894
+ execute(modelValue, { first, second }) {
895
+ if (isInterpretableValue(first.modelValue) && isInterpretableValue(second.modelValue)) {
896
+ return first.modelValue !== second.modelValue;
897
+ }
898
+ return false;
899
+ }
900
+ }
901
+ // TODO: use ref directive once on Lit-element 3
902
+ const first = renderLitAsNode(html`
903
+ <lion-input
904
+ .feedbackCondition="${(type, meta) => meta.focused}"
905
+ type="password"
906
+ name="initialPassword"
907
+ label="New password"
908
+ ></lion-input>
909
+ `);
910
+ const second = renderLitAsNode(html`
911
+ <lion-input
912
+ .feedbackCondition="${(type, meta) => meta.focused}"
913
+ type="password"
914
+ name="confirmPassword"
915
+ label="Confirm password"
916
+ ></lion-input>
917
+ `);
918
+ first.validators = [
919
+ new PasswordMatch(
920
+ { first, second },
921
+ { getMessage: () => 'Please match with confirmation field' },
922
+ ),
923
+ ];
924
+ second.validators = [
925
+ new PasswordMatch({ first, second }, { getMessage: () => 'Please match with initial field' }),
926
+ ];
927
+
928
+ export const contextValidation = () => html` ${first}${second} `;
929
+ ```