Laravel 5:使用Java验证表单的最佳方法 [英] Laravel 5: Best way to validate form with Javascript
问题描述
我想在Laravel的客户端中验证表单.有什么简单的方法吗?
I want to validate forms in the client side in Laravel. It's there any easy way to do it?
推荐答案
您可以使用软件包 Laravel 5 Javascript验证.此软件包基于 JQuery验证插件
You can use the package Laravel 5 Javascript Validation. This package enables transparent Javascript Valditaion in your views based on JQuery Validation Plugin
这是一个如何在控制器中重用验证规则的基本示例.
This is a basic example of how to reuse your validation rules in the controller.
PostController.php
namespace App\Http\Controllers;
class PostController extends Controller {
/**
* Define your validation rules in a property in
* the controller to reuse the rules.
*/
protected $validationRules=[
'title' => 'required|unique|max:255',
'body' => 'required'
];
/**
* Show the edit form for blog post
* We create a JsValidator instance based on shared validation rules
* @param string $post_id
* @return Response
*/
public function edit($post_id)
{
$validator = JsValidator::make($this->validationRules);
$post = Post::find($post_id);
return view('edit_post')->with([
'validator' => $validator,
'post' => $post
]);
}
/**
* Store the incoming blog post.
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$v = Validator::make($request->all(), $this->validationRules]);
if ($v->fails())
{
return redirect()->back()->withErrors($v->errors());
}
// do store stuff
}
}
在视图中,您只需打印传递给视图的 validator 对象. 记住,该程序包依赖于JQuery和 您必须在该 jsvalidation.js
In the view you simply should print the validator object passed to the view. Remember that this package depends of JQuery and you have to include before that jsvalidation.js
edit_post.blade.php
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<form class="form-horizontal" role="form" method="POST" action="" id="ddd">
<div class="form-group">
<label class="col-md-4 control-label">Title</label>
<div class="col-md-6">
<input type="text" class="form-control" name="title">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Array</label>
<div class="col-md-6">
<textarea name="body"></textarea>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- Scripts -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
<!-- Laravel Javascript Validation -->
<script type="text/javascript" src="{{ asset('vendor/jsvalidation/js/jsvalidation.js')}}"></script>
{!! $validator !!}
这篇关于Laravel 5:使用Java验证表单的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!