Jump to content
taviroquai

[Resolvido] jQuery plugin - validar formulário por ajax

Recommended Posts

taviroquai

Boas! :D

Há alguém com alguma disposição para me ajudar a transformar a seguinte "class" javascript num plugin para jQuery? Nunca fiz um plugin destes...

Isto é uma "classe" para validar formulários com recurso a ajax.

Como está usa-se da seguinte forma:

EDIT: agora mais simples


// create a new FormAssist with custom submit callback
var form = new FormAssist('form', function(assist, e) {
		if (!assist.result) {
			e.preventDefault();
			assist.validateAll();
		}
});

// add simple rule for just 1 input field
form.rule('key1', '#field1');

	// allow to add a composite rule  
	// a custom data callback can be specified with options
form.rule('key2', ['input[name="field2"]', '#field3']);

E já que isto não funciona sem jQuery, gostava que se usa-se da seguinte forma:


// create a new FormAssist with custom submit callback
var form = $('form').FormAssist(function(assist, e) {
if (!assist.result) e.preventDefault();
$('#form_submit').attr('disabled','disabled');
});

// o resto pode ser igual...

Aqui está um exemplo de utilização http://marcoafonso.pt/tests/validator/index.php

Aqui está o javascript...


/**
* What is this?
*
* FormAssist is a javascript utility based on jQuery and Ajax
* that allows the user to validate a form.
*
* Why???
*
* Because web application validation is a mess and normally the same form
* have splitten validation rules on client and server which leads to
* unmaintainable and buggy code.
* This centralizes validation on server, where you may also need to do database
* validation.
* Nevertheless, the main purpose is to submit the form just once!
*
* Features?
*
* - Validates single rules
* - Validates groups of rules
* - Field inline messages
*
*/

function FormAssist(selector, cb, url) {

this.selector = selector;
this.url = url;
if (typeof url !== 'string') this.url = $(selector).attr('action');
this.rules = {};
this.result = true;

var me = this;
// TODO: throw exception if not found or is not a form
$(this.selector).submit(function(e) {
	me.checkAll();
	if (typeof cb == 'function') cb(me, e);
});
}

FormAssist.prototype.checkAll = function() {

this.result = true;
for ( var key in this.rules ) {
	if (!this.rules[key].options.result) {
		this.result = false;
		break;
	}
}
}

FormAssist.prototype.validateAll = function() {
for (var key in this.rules) {
	if (!this.rules[key].result) this.validate(key);
}
}

FormAssist.prototype.validate = function(key) {
var post = {_assist_rule: key};
var items = this.rules[key].options.data();
for (var k in items) post[k] = items[k];
var me = this;
$.post(this.url, post, function(data) {
	me.rules[key].options.result = data.result;
	var msgEl = $('.assist-msg-'+key);
	if (msgEl.length > 0) {
		if (typeof me.rules[key].selector == 'string') $(me.rules[key].selector).addClass(data.type);
		else {
			for (var i = 0; i < me.rules[key].selector.length; i++) {
				$(me.rules[key].selector[i]).addClass(data.type);
			}
		}
		msgEl.html(data.msg);
	}
	me.checkAll();
	if (typeof me.rules[key].options.cb == 'function') {
		me.rules[key].options.cb(me, data);
	}
});
}


FormAssist.prototype.rule = function(key, selector, options) {

if (options === undefined) options = {};
if (options.result === undefined) options.result = 0;
if (options.data === undefined || options.data == null) {
	options.data = this.parseSelectorValues(selector);
}
this.rules[key] = {key: key, selector: selector, options: options};

var target; // TODO: throw exception if not found

if (typeof selector == 'string') {
	target = $(selector);
	this.observe(target, key);
}
else {
	for (var i = 0; i < this.rules[key].selector.length; i++) {
		target = $(this.rules[key].selector[i]);
		this.observe(target, key);
	}
}
}

FormAssist.prototype.observe = function(target, key) {
var evt = 'blur';
if (target.attr('type') == 'radio') evt = 'change';
var me = this;
target.on(evt, function(e) {
	me.validate(key);
});
}

FormAssist.prototype.parseSelectorValues = function(selector) {
var data, items = {};
var me = this;
if (typeof selector == 'string') {
	data = function() {
		var fieldName = $(selector).attr('name');
		items[fieldName] = $(selector).val();
		return items;
	};
}
else {
	data = function() {
		for (var i = 0; i < selector.length; i++) {
			var fieldName = $(selector[i]).attr('name');
			if (me.inArray($(selector[i]).attr('type'), ['checkbox', 'radio'])) {
				items[fieldName] = $(selector[i]+':checked').val();
			}
			else items[fieldName] = $(selector[i]).val();
		}
		return items;
	};
}
return data;
}

FormAssist.prototype.inArray = function(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
	if(haystack[i] == needle) return true;
}
return false;
}

Edited by taviroquai

Share this post


Link to post
Share on other sites
taviroquai

Olha... foi fácil... :D foi só colocar a minha classe dentro disto:

(function ( $ ) {

// Minha classe vai aqui...


$.fn.FormAssist = function(cb, url) {
	return new FormAssist(this, cb, url);
}

}( jQuery ));

Agora já se pode usar assim:


$('form').FormAssist()
.rule('key1', '#field1') // simple rule for just 1 field
.rule('key2', ['input[name="field2"]', '#field3']); // rule for related fields

Ou assim...


$('form').FormAssist(function(assist, e) {
		if (!assist.result) {
			e.preventDefault();
			assist.validateAll();
		}
})
.rule('key1', '#field1') // simple rule for just 1 input field
.rule('key2', ['input[name="field2"]', '#field3']); // rule for a group of fields

EDIT: exemplo com bootstrap 3 http://marcoafonso.pt/tests/validator/index.php

Edited by taviroquai
  • Vote 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.