Skip to content

Instantly share code, notes, and snippets.

@ElawadyNet
Last active August 29, 2015 14:09
Show Gist options
  • Save ElawadyNet/d6dabb25bb2783e342af to your computer and use it in GitHub Desktop.
Save ElawadyNet/d6dabb25bb2783e342af to your computer and use it in GitHub Desktop.
use laravel validation rules on client side.
<div class="form-group">
{{Form::label('label','text')}}
{{Form::text('name',$value,['class'=>'form-control lara-validation' , 'data-lara-key' => 'email','data-lara-rules' => 'required|email'])}}
<div class="lara-validation-note"></div>
</div>
Route::any('/validate', function () {
$rule = Input::get('rule');
$key = Input::get('key');
$value = Input::get('value');
$v = Validator::make([$key => $value], [$key => $rule]);
$data = $v->fails() ? ['hasError' => true, 'msg' => $v->messages()->first()] : ['hasError' => false, 'msg' => 'ok'];
return Response::json($data);
});
$(document).on('change paste', '.lara-validation', function() {
var el = $(this);
var val = el.val();
var key = el.data('laraKey');
var rule = el.data('laraRules');
$.ajax({
type: 'POST',
url: '/validate',
dataType: 'json',
data: {
rule: rule,
key: key,
value: val
},
success: function(data) {
if (data.hasError) {
el.parent('.form-group').addClass('has-error');
el.siblings('.lara-note').text('').text(data.msg);
} else {
el.parent('.form-group').removeClass('has-error').addClass('has-success');
el.siblings('.lara-note').text('');
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment