Comparison

util/dataforms.lua @ 11070:f7f30a3464fe

util.dataforms: Add support for validating (integer) ranges
author Kim Alvefur <zash@zash.se>
date Thu, 21 Nov 2019 18:56:43 +0100
parent 11026:a086825ed73a
child 11630:855b065d5fd6
comparison
equal deleted inserted replaced
11069:770a5923e959 11070:f7f30a3464fe
8 8
9 local setmetatable = setmetatable; 9 local setmetatable = setmetatable;
10 local ipairs = ipairs; 10 local ipairs = ipairs;
11 local type, next = type, next; 11 local type, next = type, next;
12 local tonumber = tonumber; 12 local tonumber = tonumber;
13 local tostring = tostring;
13 local t_concat = table.concat; 14 local t_concat = table.concat;
14 local st = require "util.stanza"; 15 local st = require "util.stanza";
15 local jid_prep = require "util.jid".prep; 16 local jid_prep = require "util.jid".prep;
16 17
17 local _ENV = nil; 18 local _ENV = nil;
52 end 53 end
53 end 54 end
54 55
55 if formtype == "form" and field.datatype then 56 if formtype == "form" and field.datatype then
56 form:tag("validate", { xmlns = xmlns_validate, datatype = field.datatype }); 57 form:tag("validate", { xmlns = xmlns_validate, datatype = field.datatype });
58 if field.range_min or field.range_max then
59 form:tag("range", {
60 min = field.range_min and tostring(field.range_min),
61 max = field.range_max and tostring(field.range_max),
62 }):up();
63 end
57 -- <basic/> assumed 64 -- <basic/> assumed
58 form:up(); 65 form:up();
59 end 66 end
60 67
61 68
288 function (field_tag) 295 function (field_tag)
289 return field_tag:get_child_text("value"); 296 return field_tag:get_child_text("value");
290 end 297 end
291 298
292 data_validators["xs:integer"] = 299 data_validators["xs:integer"] =
293 function (data) 300 function (data, field)
294 local n = tonumber(data); 301 local n = tonumber(data);
295 if not n then 302 if not n then
296 return false, "not a number"; 303 return false, "not a number";
297 elseif n % 1 ~= 0 then 304 elseif n % 1 ~= 0 then
298 return false, "not an integer"; 305 return false, "not an integer";
299 end 306 end
307 if field.range_max and n > field.range_max then
308 return false, "out of bounds";
309 elseif field.range_min and n < field.range_min then
310 return false, "out of bounds";
311 end
300 return true, n; 312 return true, n;
301 end 313 end
302 314
303 315
304 local function get_form_type(form) 316 local function get_form_type(form)