Reputation: 1548
i've been working on a validation script for client-side, that uses built-in Kohana validation, trying to do it in a way that works both client and server sides. So far i made the server side work, but i need some help improving my javascript (My javascript knowlodgement ain't that good) and finish implementing it. (Currently it works for inputs and textareas).
A random controller:
// ...
$errors = array();
if ($this->request->method() == 'POST')
{
// Post to validate/look and get the decoded array
$validate = Request::factory('validate/look')->post($this->request->post())->execute()->body();
$errors = json_decode($validate, TRUE);
// Empty array, Validation OK
if ($errors === array())
{
// anything u want here
}
}
Now, the Validation controller (which will be called from any controller, or via ajax):
class Controller_Validate extends Controller {
public function action_look()
{
//$user = $this->user->loader() ? $this->user : NULL;
//Validation
$valid = Validation::factory($this->request->post())
->rules('name', array(
array('not_empty'),
array('min_length', array(':value', 10)),
array('max_length', array(':value', 80)),
array('regex', array(':value', '/^[\pL\pN ]++$/uD')),
array(array($this, 'check_name')),
))
->rules('description', array(
array('not_empty'),
))
->rule('look_tags', array($this, 'check_tags'))
;
$valid->check();
// Only get messages for the posted fields
$resp = array_intersect_key($valid->errors('uploadlook'), $this->request->post());
$this->response->body(json_encode($resp));
}
}
And this is the javascript:
$(function(){
$('.validate').find('input,textarea').blur(function(){
var element = $(this);
var name = $(this).attr('name');
var value = $(this).val();
$.ajax({
type: 'POST',
url: '/comunidad/validate/look',
data: name + '=' + value,
success: function(e){
e = JSON.parse(e);
if(e.length !== 0) {
var msg = e[name];
var error = '<p>' + msg + '</p>';
if (element.next().length === 0) element.after(error);
else element.next().replaceWith(error);
} else {
if (element.next().length) element.next().remove();
}
}
});
});
});
I need some feedback and little help completing the javascript :)
Upvotes: 0
Views: 487
Reputation: 2882
Some feedback on the code: The validation code shoud be put in a helper and should just return an array. Then you should have an AJAX-controller that uses the helper and outputs JSON. The serverside check should only use the helper. That would be much cleaner and the json encode/decode on the server side is pretty ugly when you can just return an array.
What is wrong with the javascript?
Upvotes: 1