json - javascript recursive validation -
i want validate json tree conditions (and, not, or) , id keys. that:
{ "or": [ { "and": [ { "not": [ { "id": 2 } ] }, { "id": 2 } ] }, { "and": [ { "id": 3 }, { "id": 3 } ] } ] }
this valid tree. if json contains other operations or has empty ([], {}) invalid. example,
{ "x": [ //invalid tag { "and": [ { "not": [ { //empty } ] }, { "id": 2 } ] }, { "and": [ { "id": 3 }, { "id": 3 } ] } ] }
my code:
var validaterule = function (js) { console.log('current validation ' + json.stringify(js)); if (js.hasownproperty('or')) { return js.hasownproperty('length') ? js.length > 0 && validaterule(js.or) : validaterule(js.or); } if (js.hasownproperty('and')) { return js.hasownproperty('length') ? js.length > 0 && validaterule(js.and) : validaterule(js.and); } if (js.hasownproperty('not')) { return js.hasownproperty('length') ? js.length > 0 && validaterule(js.not) : validaterule(js.not); } if (js.hasownproperty('length')) { //json array if (js.length == 0) { return false; } else if (js.length == 1) { return js[0].hasownproperty('id'); } else { (var key in js) { if (js.hasownproperty(key)) { return validaterule(js[key]); } } } } else { return js.hasownproperty('id'); } };
but since in loop have 'return' code not work properly. give me advice please.
exceptions perhaps cleanest way pass failures around in nested validation. example,
function classof(p) { return {}.tostring.call(p).slice(8, -1); } function check(expr) { if(classof(expr) != "object") throw syntaxerror("object expected"); if(!object.keys(expr).length) throw syntaxerror("empty object"); return object.keys(expr).foreach(function(key) { var val = expr[key]; switch(key) { case "and": case "or": case "not": if(classof(val) != "array") throw syntaxerror("array expected"); if(key == "not" && val.length !== 1) throw syntaxerror("incorrect number of arguments"); if(key != "not" && val.length < 2) throw syntaxerror("incorrect number of arguments"); val.foreach(check); break; case "id": if(classof(val) != "number") throw syntaxerror("number expected"); break; default: throw syntaxerror("invalid operator " + key); } }); }
the top-level code bit ugly, since js doesn't support typed catch
blocks, unavoidable:
try { check(expr); // expression valid, move on } catch(e) { if(e instanceof syntaxerror) // expression invalid, handle else // else went wrong throw e; }
Comments
Post a Comment