Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Valid function #6

Merged
merged 9 commits into from
May 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -18,6 +18,7 @@ A library for Lua to validate various values and table structures.
- [`valid.arrayof`](#validarrayof)
- [`valid.map`](#validmap)
- [`valid.mapof`](#validmapof)
- [`valid.func`](#validfunc)
- [Error Handling and Invalid Propagation](#error-handling-and-invalid-propagation)
- [Contributing](#contributing)
- [License](#license)
@@ -384,6 +385,28 @@ assert(not is_valid) -- false, "name" is required for "bob"
* `empty`: Set to `true` to allow empty maps.
* `func`: A table containing two custom validation functions, one for the keys and one for the values.

### `valid.func`

Validates that a value is a function.

#### Usage

```lua
local valid = require "valid"

local valid_function = valid.func()

local is_valid = valid_function(function() end)
assert(is_valid) -- true

local is_valid = valid_function("123")
assert(not is_valid) -- false, not a function
```

#### Parameters

*(none)*

## Error Handling and Invalid Propagation

The library provides detailed error information when validation fails. When `is_valid` is `false`, additional values are provided to help identify the nature of the validation failure:
28 changes: 28 additions & 0 deletions tests.lua
Original file line number Diff line number Diff line change
@@ -74,7 +74,35 @@ describe("Validation Library Tests", function()
}
}

local simple_function = function() end

local tests = {
-- Valid simple function
{
description = "Valid simple function",
definition = valid.func(),
data = simple_function,
expected = {
is_valid = true,
val_or_err = simple_function,
badval_or_nil = nil,
path_or_nil = nil
}
},

-- Invalid function
{
description = "Invalid function",
definition = valid.func(),
data = "123",
expected = {
is_valid = false,
val_or_err = "func",
badval_or_nil = "123",
path_or_nil = nil
}
},

-- Valid contact data
{
description = "Valid contact data",
11 changes: 11 additions & 0 deletions valid.lua
Original file line number Diff line number Diff line change
@@ -339,4 +339,15 @@ local function mapof(deffuncs, opts)
end
_M.mapof = mapof

local function func()
return function(val)
if type(val) ~= "function" then
return false, "func", val
end

return true, val
end
end
_M.func = func

return _M