Laravel:如何使用jQuery验证来测试数据库中是否已存在某些东西[重复]

问题描述 投票:0回答:1

此问题已经在这里有了答案:

我正在学习laravel。我已经在我的项目中使用jQuery验证reference实现了客户端验证。

首先,我的应用客户端验证工作正常。但是现在我想访问数据库以给出已经存在或不存在的错误(服务器端验证)。我已经在控制器中进行了编码,但是由于服务器端验证,我的客户端验证无法正常工作。

控制器代码

public function store(Request $request)
{
    $user = Auth::user();

    $apmcRecord = AgriculturalProduceMarketCommettee::where('apmc_branch_name', $request->apmc_branch_name)
        ->first();
    if ( !empty($apmcRecord) ) {
        return redirect()->back()->with('error', 'APMC Branch already exists!');
    } else {
        $apmc = new AgriculturalProduceMarketCommettee();
        $apmc->apmc_branch_name = $request->apmc_branch_name;
        $apmc->apmc_city_name = $request->apmc_city_name;
        $apmc->is_active = '1';
        $apmc->created_by = 'A'.$user->role_id;
        $apmc->updated_by = '0';
        $apmc->save();
        return redirect()->back()->with('success', 'APMC Branch created');
    }
}

Jquery验证码

$("#apmc_create").each(function () {
    $(this).validate({
        rules: {
            apmc_branch_name: {
                required: true,
                maxlength: 30,
                nameRegex: true,
            },
            apmc_city_name: {
                required: true,
            },
        },
        messages: {
            apmc_branch_name: {
                required: "<font color='red' size='1'>Please enter the branch name",
                maxlength: "<font color='red' size='1'>Please enter no more than 30 characters",
                nameRegex: "<font color='red' size='1'>Please enter Letters, numbers, and spaces only",
            },
            apmc_city_name: {
                required: "<font color='red' size='1'>Please enter the city name",

            },
        }
    });
});

以上代码未向我显示我的客户端验证,因为我包含服务器端错误消息。我认为这是由于服务器验证和客户端验证合并造成的问题。一种可能的解决方案是在jquery验证中使用AJAX。但是我没有在MVC框架和jquery验证中使用AJAX,所以没有解决方案。

以上验证用于创建。我也必须同样申请编辑。

请帮我解决以上情况或其他解决方案中如何在ajax验证中使用ajax。

提前感谢。

jquery ajax laravel jquery-validate
1个回答
0
投票

请更改您的代码。

 $apmcRecord = AgriculturalProduceMarketCommettee::where('apmc_branch_name', $request->apmc_branch_name)->count();

 $apmcRecord = AgriculturalProduceMarketCommettee::where('apmc_branch_name', $request->apmc_branch_name)->first();

 $apmcRecord = AgriculturalProduceMarketCommettee::where('apmc_branch_name', $request->apmc_branch_name)->get();
© www.soinside.com 2019 - 2024. All rights reserved.