Skip to content

Instantly share code, notes, and snippets.

@vaclavbohac
Created February 18, 2010 14:15
Show Gist options
  • Save vaclavbohac/307682 to your computer and use it in GitHub Desktop.
Save vaclavbohac/307682 to your computer and use it in GitHub Desktop.
var nette = nette || { };
nette.getValue = function(elem) {
if (!elem) {
var undefined;
return undefined;
}
if (!elem.nodeName) { // radio
for (var i = 0, len = elem.length; i < len; i++) {
if (elem[i].checked) {
return elem[i].value;
}
}
return null;
}
if (elem.nodeName.toLowerCase() === 'select') {
var index = elem.selectedIndex, options = elem.options;
if (index < 0) {
return null;
} else if (elem.type === 'select-one') {
return options[index].value;
}
for (var i = 0, values = [], len = options.length; i < len; i++) {
if (options[i].selected) {
values.push(options[i].value);
}
}
return values;
}
if (elem.type === 'checkbox') {
return elem.checked;
}
return elem.value.replace(/^\s+|\s+$/g, '');
}
nette.getFormValidators = function(form) {
var name = form.getAttributeNode('name').nodeValue;
return this.forms[name] ? this.forms[name].validators : [];
}
nette.validateControl = function(control) {
var validator = this.getFormValidators(control.form)[control.name];
return validator ? validator(control) : null;
}
nette.validateForm = function(sender) {
var form = sender.form || sender;
var validators = this.getFormValidators(form);
for (var name in validators) {
var error = validators[name](sender);
if (error) {
if (form[name].focus) {
form[name].focus();
}
alert(error);
return false;
}
}
return true;
}
nette.toggle = function(id, visible) {
var elem = document.getElementById(id);
if (elem) {
elem.style.display = visible ? "" : "none";
}
}
nette.forms = nette.forms || { };
nette.forms["frm-MyForm"] = {
validators: {
"name": function(sender) {
var res, form = sender.form || sender;
var val = nette.getValue(form["name"]); res = val!='' && val!="";
if (!res) return "Your name is required!";
},
"mail": function(sender) {
var res, form = sender.form || sender;
var val = nette.getValue(form["mail"]); res = val!='' && val!="";
if (!res) return "Your email is required!";
res = /^[^@\s]+@[^@\s]+\.[a-z]{2,10}$/i.test(nette.getValue(form["mail"]));
if (!res) return "You email is not in the correct form!";
}
},
toggle: function(sender) {
var visible, res, form = document.forms["frm-MyForm"];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment