Laravel未验证html选择框

1u4esq0p  于 2023-01-10  发布在  其他
关注(0)|答案(2)|浏览(78)

我有问题与验证html选择。我把规则和所有其他表单控件工作正常,但只有选择不显示验证消息。

    • 型号**
class Post extends Model
{
    
    protected $table = 'post';

   
static $rules = [
'title' => 'required',
    'slug' => 'required',
'user_id' => 'required|not_in:0',
    'meta_title' => 'required',
    'meta_description' => 'required',
'post_category_id' => 'required'
];
}

"刀锋"

<div class="form-group">
    {{ Form::label('post_category_id', 'Category') }}
    <select name="post_category_id" class="form-control">
        <option value="0">Select Category</option>
        @foreach($categories as $category)
        <option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
        @endforeach
    </select> {!! $errors->first('post_category_id', '<div class="invalid-feedback">:message</div>') !!}
</div>
    • 主计长**
public function store(Request $request)
    {
        request()->validate(Post::$rules);

        $post = Post::create($request->all());

        Alert::alert('Success', 'Post created successfully.', 'Type');

        return redirect()->route('admin.post.index');
    }

我做错了什么?

zrfyljdw

zrfyljdw1#

即使该选项的值为0,它仍然存在,因此“必需”规则不会触发任何错误
请改用禁用的选项

<select name="post_category_id" class="form-control">
    <option disabled>Select a Category</option>
    @foreach($categories as $category)
        <option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
    @endforeach
</select>
0lvr5msh

0lvr5msh2#

据我所知,您在select的占位符上设置了默认值,因此输入将始终有效,因为它始终发送到后端。请看这一行:选择要设置默认值的类别,将其删除,然后重试:
在刀片中执行以下操作:

<div class="form-group">
    {{ Form::label('post_category_id', 'Category') }}
    <select name="post_category_id" class="form-control">
        <option>Select Category</option>
        @foreach($categories as $category)
        <option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
        @endforeach
    </select> {!! $errors->first('post_category_id', '<div class="invalid-feedback">:message</div>') !!}
</div>

相关问题