My old SSFormValidator
This was one of my first attempts at JavaScript and MooTools a few years ago, surprisingly awesome, if that's not too cocky to say :P
HTML
<form id=form action="/echo/json/" method="post">
<p>First Name<br>
<input type=text name=first_name>
<span errorFor=first_name></span>
</p>
<p>Last Name<br>
<input type=text name=last_name>
<span errorFor=last_name></span>
</p>
<p>
Fake JSON response
<input type="text" name=json id=echo style="width: 80%"><br>
</p>
<p>
<input type=hidden name=delay value=2>
<input type=submit>
</p>
</form>
CSS
p {
margin: 1em 0;
font-size: 16px;
}
input {
font-size: 16px;
}
input.error {
background: #ecc;
border: solid 1px #e33;
}
span {
color: red;
}
JavaScript
window.addEvent('domready', function() {
var data = {
errors: {
'first_name': 'Certainly you have a first name',
'last_name': 'Please enter your last name'
}
};
$('echo').set('value', JSON.encode(data));
new SSFormValidator('form');
});
Request.JSON.Form = new Class({
Extends: Request.JSON,
initialize: function(form, options) {
this.parent(options);
this.form = document.id(form);
this.options.url = this.form.get('action');
this.options.method = this.form.get('method');
this.boundHandler = this.submit.bind(this);
this.attach();
},
attach: function() {
this.form.addEvent('submit', this.boundHandler);
return this;
},
detach: function() {
this.form.removeEvent('submit', this.boundHandler);
return this;
},
submit: function(event) {
event.stop();
//console.log('here')
this.post(this.form);
}
});
var SSFormValidator = new Class({
Extends: Request.JSON.Form,
options: { /* onValidation: $empty, */
errorClass: 'error',
errorAttribute: 'errorFor',
errorVariable: 'errors'
},
onSuccess: function(response) {
this.validate(response);
return this;
},
validate: function(response) {
this.removeErrors();
if (response[this.options.errorVariable]) {
var elements = this.getInvalidElements(response[this.options.errorVariable]);
elements[0].select();
}
else this.fireEvent('onValidation', response);
return this;
},
removeErrors: function() {
this.form.getElements('.' + this.options.errorClass).each(function(el) {
var errorEl = el.retrieve('errorEl');
errorEl.set('html', '');
el.removeClass(this.options.errorClass);
}.bind(this));
},
getInvalidElements: function(obj) {
for (i in...