Skip to content

Commit 6202be4

Browse files
authored
Merge pull request #12 from willothy/feat-validator-combinators
Feat validator combinators
2 parents 087030d + c627111 commit 6202be4

File tree

2 files changed

+48
-6
lines changed

2 files changed

+48
-6
lines changed

docs/pages/docs/components/form.mdx

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,14 @@ n.form(
3838

3939
#### on_submit
4040

41-
<Property
41+
<Property
4242
defaultValue="fn.ignore"
4343
types={['fun(is_valid: boolean): nil']}
4444
/>
4545

4646
#### submit_key
4747

48-
<Property
48+
<Property
4949
defaultValue="<C-CR>"
5050
types={['string[]', 'string']}
5151
/>
@@ -63,4 +63,11 @@ Available validation functions:
6363
- `equals`
6464
- `contains`
6565

66+
Available combinators:
67+
68+
- `all`: ensures all validators pass
69+
- `any`: ensures at least one validator passes
70+
- `none`: ensures no validators pass
71+
- `compose` (deprecated, use `all`)
72+
6673

lua/nui-components/validators.lua

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
local M = {}
22

3+
---@type fun(min: integer): fun(arg: string): boolean
34
function M.min_length(min)
45
return function(arg)
56
return #arg >= min
67
end
78
end
89

10+
---@type fun(arg: string): boolean
911
M.is_not_empty = M.min_length(1)
1012

1113
function M.max_length(max)
@@ -14,23 +16,52 @@ function M.max_length(max)
1416
end
1517
end
1618

19+
---@type fun(pattern: string): fun(arg: string): boolean
1720
function M.contains(pattern)
1821
return function(arg)
19-
return string.find(arg, pattern)
22+
return string.find(arg, pattern) ~= nil
2023
end
2124
end
2225

26+
---@type fun(value: any): fun(arg: any): boolean
2327
function M.equals(value)
2428
return function(arg)
2529
return vim.deep_equal(value, arg)
2630
end
2731
end
2832

29-
function M.compose(...)
30-
local tbl = { ... }
33+
---@type fun(...: fun(arg: any): boolean): fun(arg: any): boolean
34+
function M.none(...)
35+
local validators = { ... }
36+
return function(value)
37+
for _, fn in ipairs(validators) do
38+
if fn(value) then
39+
return false
40+
end
41+
end
42+
return true
43+
end
44+
end
45+
46+
---@type fun(...: fun(arg: any): boolean): fun(arg: any): boolean
47+
function M.any(...)
48+
local validators = { ... }
49+
return function(value)
50+
for _, fn in ipairs(validators) do
51+
if fn(value) then
52+
return true
53+
end
54+
end
55+
return false
56+
end
57+
end
58+
59+
---@type fun(...: fun(arg: any): boolean): fun(arg: any): boolean
60+
local function all(...)
61+
local validators = { ... }
3162

3263
return function(value)
33-
for _, fn in ipairs(tbl) do
64+
for _, fn in ipairs(validators) do
3465
if not fn(value) then
3566
return false
3667
end
@@ -40,4 +71,8 @@ function M.compose(...)
4071
end
4172
end
4273

74+
M.all = all
75+
76+
M.compose = all
77+
4378
return M

0 commit comments

Comments
 (0)