diff --git a/README.md b/README.md index 4a21acb..ef8ec43 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/tests.lua b/tests.lua index a97c622..b76faf8 100644 --- a/tests.lua +++ b/tests.lua @@ -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", diff --git a/valid.lua b/valid.lua index e79931b..ac76bf3 100644 --- a/valid.lua +++ b/valid.lua @@ -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