Laravel 4 validation in bootstrap modal

拜拜、爱过 提交于 2019-12-06 14:38:59

Your best bet would be to validate the form via AJAX to avoid the page reloading entirely. You would then check the response of your AJAX request for the presence of errors and show them inside the modal if they exist.

You could also add in client side validation to prevent the request being made until the rules are satisfied. I wouldn't recommend using this INSTEAD of server side validation but using it ASWELL as is normally quite desirable.

To accomplish this, you'd need to do something along these lines:

Javascript:

Catch submit event of your form and make an AJAX request.

$(document).on('submit', 'form', function(event){
    event.preventDefault();

    var data = { avatar_src: $("#avatar_src").val(); };

    $.ajax({
        url: "/dashboard/avatar",
        data: data
        type: "POST",
    }).done(function(response) {
        if(response.errors)
        {
            // Add error to Modal Body
        }
        else
        {
            // Show success message, close modal?
        }
    });
});

Backend:

Modify your controller method to detect if the current request is an AJAX request and if so, return the response in JSON instead of Redirecting. For example:

if(Request::ajax())
{
    return Response::json(array('errors' => $validator->messages()));
}
else
{
    return Redirect::back()->withErrors($validator);
}

I've not tested any of that code so might contain some typos/errors but hopefully this helps you!

I was facing same issue. After research on internet,I found that Laravel don't support withSuccess('success_msg') method.

     return Redirect::to('dashboard')->withSuccess("Success: avatar updated."); 

Here is complete discussion on this topic: https://github.com/laravel/framework/issues/906.

But you can handle this issue with this approach:-

- For Error message:-

[code has to be added in controller]

return Redirect::to('view')->withErrors('your error message.');

[code has to be added in view]

@if(isset($errors) && count($errors->all())>0)
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif

- for succcess message:-

[code has to be added in controller]

$success_msg='your success message.';
Session::flash('successMsg', $success_msg);
return Redirect::to('view');

[code has to be added in view]

@if (Session::has('successMsg'))
{{ Session::get('successMsg') }}
@endif

This approach is working fine for me. For better display of your errors you can use bootstrap css.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!