You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel模态表单唯一字段验证时弹窗内显示错误的实现

解决Laravel模态表单验证错误不显示在模态内的问题

方案一:同步提交+自动保持模态打开(适合新手)

无需修改核心提交逻辑,仅通过视图调整实现验证失败时模态自动打开、保留用户输入并展示错误。

1. 优化视图输入框:保留旧值+字段级错误提示

给模态内的表单输入框添加旧值填充和错误样式,确保验证失败后用户输入不丢失,错误提示精准对应字段:

<!-- CurrencyName输入框修改 -->
<div class="form-group row">
    <label for="txtcurrencyname" class="col-lg-2 col-form-label">currency name</label>
    <div class="col-lg-10">
        <input type="text" class="form-control @error('CurrencyName') is-invalid @enderror" 
               id="txtcurrencyname" name="CurrencyName" 
               value="{{ old('CurrencyName') }}" required>
        <!-- 字段专属错误提示 -->
        @error('CurrencyName')
            <div class="invalid-feedback">{{ $message }}</div>
        @enderror
    </div>
</div>

<!-- price1输入框同理修改 -->
<div class="form-group row">
    <label for="txtcurrencyprice1" class="col-lg-2 col-form-label">price1</label>
    <div class="col-lg-10">
        <input type="number" class="form-control @error('txtcurrencyprice1') is-invalid @enderror" 
               id="txtcurrencyprice1" name="txtcurrencyprice1" 
               value="{{ old('txtcurrencyprice1') }}" step="any" required>
        @error('txtcurrencyprice1')
            <div class="invalid-feedback">{{ $message }}</div>
        @enderror
    </div>
</div>

2. 添加自动打开模态的脚本

在视图底部(模态代码之后)加入以下脚本,当存在验证错误时,页面加载自动触发模态显示:

<script>
@if($errors->any())
    $(document).ready(function(){
        $('#modaldemo8').modal('show');
    });
@endif
</script>

3. 控制器无需修改

现有store方法的validate逻辑已正确处理验证,失败时Laravel会自动返回上一页并携带错误信息与旧输入,配合视图修改即可实现模态内显示错误且不关闭。


方案二:AJAX异步提交(体验更流畅)

通过AJAX提交表单,完全避免页面刷新,错误提示与模态状态完全可控。

1. 修改视图:给表单添加ID并预留错误容器

<form class="needs-validation was-validated" id="currencyForm" action="{{ route('currencies.store') }}" method="POST">
    @csrf
    <!-- 原有表单内容不变,保留旧值与字段错误提示 -->
    ...
    <!-- 新增全局错误提示容器 -->
    <div id="formErrors" class="alert alert-danger d-none"></div>
</form>

2. 添加AJAX提交脚本

在视图底部加入:

<script>
$(document).ready(function(){
    $('#currencyForm').on('submit', function(e){
        e.preventDefault(); // 阻止默认同步提交
        let form = $(this);
        let url = form.attr('action');
        let data = form.serialize();

        // 清空历史错误提示
        $('#formErrors').addClass('d-none').empty();
        form.find('.is-invalid').removeClass('is-invalid');
        form.find('.invalid-feedback').empty();

        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            success: function(){
                // 提交成功:关闭模态并刷新页面
                $('#modaldemo8').modal('hide');
                location.reload();
            },
            error: function(xhr){
                if(xhr.status === 422){
                    let errors = xhr.responseJSON.errors;
                    // 渲染全局错误列表
                    let errorList = '<ul>';
                    $.each(errors, function(key, value){
                        errorList += '<li>' + value[0] + '</li>';
                        // 标记错误字段并显示字段提示
                        form.find('[name="' + key + '"]').addClass('is-invalid').siblings('.invalid-feedback').text(value[0]);
                    });
                    errorList += '</ul>';
                    $('#formErrors').removeClass('d-none').html(errorList);
                }
            }
        });
    });
});
</script>

3. 调整控制器返回响应

修改store方法,成功时返回JSON响应:

public function store(Request $request)
{
    $validatedData = $request->validate(
        [
            'CurrencyName' => ['unique:tblcurrencies', 'max:50'],
            'txtcurrencyprice1' => ['required', 'numeric'],
            'txtcurrencyprice2' => ['required', 'numeric']
        ],
        [
            'CurrencyName.unique' => 'err1!',
            'CurrencyName.max' => 'err2!',
            'txtcurrencyprice1.required' => 'price1不能为空',
            'txtcurrencyprice2.required' => 'price2不能为空'
        ]
    );

    Currency::create(
        [
            'CurrencyRef' => Helper::GetNewRef(),
            'CurrencyName' => $request['CurrencyName'],
            'CurrencyPrice1' => $request['txtcurrencyprice1'],
            'CurrencyPrice2' => $request['txtcurrencyprice2'],
            'CurrentUser' => auth()->id()
        ]
    );
    
    return response()->json(['success' => true], 200);
}

内容的提问来源于stack exchange,提问作者M.J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:42:03