gpt4 book ai didi

Laravel 5 : Best way to validate form with Javascript

转载 作者:行者123 更新时间:2023-12-04 01:56:32 26 4
gpt4 key购买 nike

我想在 Laravel 的客户端验证表单。有什么简单的方法可以做到吗?

最佳答案

您可以使用包 Laravel 5 Javascript Validation .此包基于 JQuery Validation Plugin 在您的 View 中启用透明的 Javascript Valditaion

这是如何在 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
}
}

在 View 中,您只需打印传递给 View 的验证器对象。 记住 这个包依赖于 JQuery 和
你必须在 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 : Best way to validate form with Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28762376/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com