我在Laravel中有一个表单,我希望根据复选框验证三个文本字段。它是一个编辑用户表单,如果我选择是,我只想更新密码。这是我认为的形式:
<section>
<div class="form">
<h1>Edit: {!! $user->name !!}</h1>
{!! Form::model($user, ['method' => 'PATCH', 'action' => ['AccountController@update', $user->id], 'files' => true]) !!}
<p>Name: {!! Form::text('name') !!}
<p>Email: {!! Form::text('email') !!}
<p>Update Password? (tick for yes) {!! Form::checkbox('updatepasswordcheck', 0, false) !!}
<p>Old Password: {!! Form::password('oldpassword') !!}
<p>New Password: {!! Form::password('newpassword') !!}
<p>New Password Confirm: {!! Form::password('newpasswordconfirm') !!}
@if($user->role_id == 1)
<p> User Role: {!! Form::select('user_type', ['admin', 'guest'], '1') !!}
@else
<p> User Role: {!! Form::select('user_type', ['admin', 'guest'], '0') !!}
@endif
<p>{!! Form::submit('Update') !!}
{!! Form::close() !!}
@include ('errors.list_errors')
</div>
</section>
然后我有一个名为EditAccountRequest的请求,如下所示:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class EditAccountRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
if($this->inputs['updatepasswordcheck'])
{
$rules['oldpassword'] = 'required';
$rules['newpassword'] = 'required';
$rules['newpasswordconfirm'] = 'required';
}
$rules['name'] = 'required|min:3';
$rules['email'] = 'required|email';
return $rules;
}
}
我的问题是,当我看到复选框'updatepasswordcheck'为真时,它永远不会起作用,因为输入始终显示为null。任何人都知道如何解决这个问题?
答案 0 :(得分:5)
好的,我把它解决了。我做到了这一点并且有效:
public function rules()
{
if($this->has('updatepasswordcheck'))
{
$rules['oldpassword'] = 'required';
$rules['newpassword'] = 'required';
$rules['newpasswordconfirm'] = 'required';
}
$rules['name'] = 'required|min:3';
$rules['email'] = 'required|email';
return $rules;
}
答案 1 :(得分:3)
您可以执行以下操作:
public function rules(Request $request)
{
if($request->has('updatepasswordcheck')
{
$rules['oldpassword'] = 'required';
$rules['newpassword'] = 'required';
$rules['newpasswordconfirm'] = 'required';
}
$rules['name'] = 'required|min:3';
$rules['email'] = 'required|email';
return $rules;
}
答案 2 :(得分:2)
我正在使用Laravel 5.5并且此代码工作正常,我的情况是如果“公司信息”下拉列表选择“是”,则应该需要“公司名称”。
控制器:
@Grab('com.amazonaws:aws-java-sdk:1.11.205')
import ...
查看:
protected function validator(array $data)
{
return Validator::make($data, [
'company_name' => 'required_if:is_company,1',
]);
}
答案 3 :(得分:2)
更简洁直接的解决方案
$validated = $request->validate([
.
.
.
'newpasswordconfirm' => 'required|accepted',
'oldpassword' => 'required',
'newpassword' => $request->newpasswordconfirm === 'yes' ? 'required': 'nullable',
]);