Skip to content

Instantly share code, notes, and snippets.

@kopiro
Created July 28, 2014 14:53
Show Gist options
  • Save kopiro/0a91dffca62d98074f73 to your computer and use it in GitHub Desktop.
Save kopiro/0a91dffca62d98074f73 to your computer and use it in GitHub Desktop.
Bootstrap + Laravel | Server Side validation
<?php
$validator = Validator::make(Input::all(),
[
'name' => 'required',
'city' => 'required',
'address' => 'required',
'country' => 'required',
'site' => 'required',
'phone' => 'required',
'email' => 'required|email',
'vat' => 'required',
],
[
'name.required' => 'Il nome è un campo richiesto',
'city.required' => 'La città è un campo richiesto',
'address.required' => "L'indirizzo è un campo richiesto",
'country.required' => 'La provincia è un campo richiesto',
'site.required' => 'Il sito web è un campo richiesto',
'phone.required' => 'Il campo telefono è un campo richiesto',
'email.required' => "L'email è un campo richiesto",
'email.email' => "L'email deve essere un'email valida",
'vat.required' => "La P.IVA è un campo richiesto",
]);
if ($validator->fails()) {
return Response::json([
'error' => true,
'message' => $validator->messages()->first(),
'validation' => current((array)$validator->messages())
], 400);
}
$('[data-ajax]').submit(function(e){
e.preventDefault();
var $form = $(this);
api($form.attr('method'), $form.attr('action'), $form.serialize(), function(resp){
var cb = window[$form.data('ajax')];
if (typeof cb==='function') return cb(resp);
if (resp.reload) return location.reload();
if (resp.redirect) return (location.href = resp.redirect);
if ($form.data('validation') && resp.validation) {
$form.find('.has-error').removeClass('has-error');
$form.find('.help-block-error').remove();
$.each(resp.validation, function(k,v){
var $input = $form.find('[name="'+k+'"]');
if (!$input.length) return;
var $group = $input.parents('.form-group');
if ($group.length) {
$group.addClass('has-error');
$group.append('<div class="help-block help-block-error">'+v.join('<br>')+'</div>');
} else {
$input.addClass('has-error');
}
});
} else if (resp.message) {
$('#api-modal-text').html(resp.message);
$('#api-modal').modal('show');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment