diff options
author | Kim Alvefur <zash@zash.se> | 2019-11-21 18:56:43 +0100 |
---|---|---|
committer | Kim Alvefur <zash@zash.se> | 2019-11-21 18:56:43 +0100 |
commit | bc20052a9b53c466db12e7d35cf6c073c0ee5a3e (patch) | |
tree | 68e1211a50cbbc77e8f7e125a2027585d44c7fa6 | |
parent | 1f159505104015652a3571756aaa71112938c4e9 (diff) | |
download | prosody-bc20052a9b53c466db12e7d35cf6c073c0ee5a3e.tar.gz prosody-bc20052a9b53c466db12e7d35cf6c073c0ee5a3e.zip |
util.dataforms: Add support for validating (integer) ranges
-rw-r--r-- | spec/util_dataforms_spec.lua | 9 | ||||
-rw-r--r-- | util/dataforms.lua | 14 |
2 files changed, 22 insertions, 1 deletions
diff --git a/spec/util_dataforms_spec.lua b/spec/util_dataforms_spec.lua index 0df9fb1d..d2d1264a 100644 --- a/spec/util_dataforms_spec.lua +++ b/spec/util_dataforms_spec.lua @@ -423,6 +423,8 @@ describe("util.dataforms", function () name = "number", type = "text-single", datatype = "xs:integer", + range_min = -10, + range_max = 10, }, }; @@ -437,6 +439,13 @@ describe("util.dataforms", function () assert.table(e); assert.string(e.number); end); + + it("works", function () + local d,e = f:data(f:form({number = 100})); + assert.not_equal(100, d.number); + assert.table(e); + assert.string(e.number); + end); end); describe("media element", function () it("produced media element correctly", function () diff --git a/util/dataforms.lua b/util/dataforms.lua index 449c1a58..efb13ac9 100644 --- a/util/dataforms.lua +++ b/util/dataforms.lua @@ -10,6 +10,7 @@ local setmetatable = setmetatable; local ipairs = ipairs; local type, next = type, next; local tonumber = tonumber; +local tostring = tostring; local t_concat = table.concat; local st = require "util.stanza"; local jid_prep = require "util.jid".prep; @@ -54,6 +55,12 @@ function form_t.form(layout, data, formtype) if formtype == "form" and field.datatype then form:tag("validate", { xmlns = xmlns_validate, datatype = field.datatype }); + if field.range_min or field.range_max then + form:tag("range", { + min = field.range_min and tostring(field.range_min), + max = field.range_max and tostring(field.range_max), + }):up(); + end -- <basic/> assumed form:up(); end @@ -290,13 +297,18 @@ field_readers["hidden"] = end data_validators["xs:integer"] = - function (data) + function (data, field) local n = tonumber(data); if not n then return false, "not a number"; elseif n % 1 ~= 0 then return false, "not an integer"; end + if field.range_max and n > field.range_max then + return false, "out of bounds"; + elseif field.range_min and n < field.range_min then + return false, "out of bounds"; + end return true, n; end |