Skip to content

Instantly share code, notes, and snippets.

@zentooo
Created December 6, 2011 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zentooo/1438722 to your computer and use it in GitHub Desktop.
Save zentooo/1438722 to your computer and use it in GitHub Desktop.
;(function($) {
var key = "__schema__";
var attrMap = {
required: "required",
pattern: "pattern",
step: "divisibleBy",
min: "minimum",
max: "maximum",
maxlength: "maxLength"
};
var typeMap = {
text: { key: "type", value: "string" },
date: { key: "format", value: "date" },
datetime: { key: "format", value: "datetime" },
month: { key: "pattern", value: /\d\d\d\d-\d\d/ },
week: { key: "pattern", value: /\d\d\d\d-W\d\d/ },
time: { key: "format", value: "time" },
search: { key: "type", value: "string" },
tel: { key: "format", value: "phone" },
url: { key: "format", value: "uri" },
email: { key: "format", value: "email" }, // multiple?
color: { key: "format", value: "color" }
};
$(function() {
var i = 0, iz = document.forms.length;
for ( ; i < iz; ++i ) {
addJsonSchema(document.forms[i]);
}
});
function addJsonSchema(form) {
var $form = $(form),
$input = $("<input>"),
schema = { name: "form" };
$form.bind("submit", function() {
if ( form.noValidate ) {
return true;
}
$("input", form).each(function(i, input) {
if ( input.name.length > 0 ) {
schema[input.name] = ruleToSchema(input);
}
});
$input.attr("type", "hidden");
$input.val(JSON.stringify(schema));
$form.append($input);
return false;
});
}
function ruleToSchema(input) {
var $input = $(input), rule = {}, cur, key;
if ( $input.attr("required") ) {
rule.required = true;
}
if ( cur = $input.attr("type") ) {
addRuleByType(rule, cur);
}
for ( key in attrMap ) if ( attrMap.hasOwnProperty(key) ) {
if ( cur = $input.attr(key) ) {
rule[attrMap[key]] = cur;
}
}
return rule;
}
function addRuleByType(rule, type) {
var r = typeMap[type], str;
if ( r ) {
if ( r.key === "pattern" ) {
str = r.value.toString();
rule[r.key] = str.substr(1, str.length - 2);
}
else {
rule[r.key] = r.value;
}
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment