Skip to content

Instantly share code, notes, and snippets.

@tjstebbing
Last active August 29, 2015 14:13
Show Gist options
  • Save tjstebbing/de08d79e47c34f9e043f to your computer and use it in GitHub Desktop.
Save tjstebbing/de08d79e47c34f9e043f to your computer and use it in GitHub Desktop.
var ht = require('hudson-taylor');
var sanitize = require('sanitize-caja');
//XXX This MUST be invoked before any of our libs are loaded, overrides
//ht-schema's String validator.
ht.validators.add("String", makeParser(strParser, null));
function strParser(args, childValidators, data) {
args = merge(args, {min: null, max : null, enum : null, raw : false});
if(!data && !args.opt) throw new Error("required String");
if(!data && args.opt) return {htDeleteKey : true};
var type = typeof data;
if(type !== "string") throw new Error("required String, recieved " + type+", "+data);
if(args.min !== null && data.length < args.min) {
throw new Error("string length must be greater than "+args.min);
}
if(args.max !== null && data.length > args.max) {
throw new Error("string length must be less than or equal to "+args.max);
}
if(Array.isArray(args.enum)) {
var match = false;
for(var i=0; i<args.enum.length; i++) {
if(args.enum[i] == data) {
match = true;
break;
}
}
if(!match) throw new Error("string does not match enum: "+args.enum);
}
if(args.raw) return data;
return sanitize(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment