从客户端调用Laravel验证

Invoking the Laravel Validation from the clients end

本文关键字:验证 Laravel 调用 客户端      更新时间:2023-09-26

是否有方法在客户端使用与Laravel后端中使用的验证算法相同的验证算法。我试图在用户提交表单之前向他们表示验证状态。

这样一来,通过一项测试而不通过另一项测试,并向最终用户提供不可靠的信息将是毫无疑问的。

我使用的Laravel验证方法是

$this->validate($request, [

我知道每次表单状态通过AJAX更改时,我都可以将值发布到后端函数。但我想,每次更改都这样做会有点耗费资源,当用户离开表单时这样做会更好,但还是有点多。如果我错了,请纠正我。感谢您的任何意见,非常感谢!

因此,在Laravel 5中,您可以在数据进入控制器之前进行验证。

你必须做的事情:(简单的例子,用于州一级的条目验证)

  1. app/Http/Request'Validator中创建一个文件,将其命名为StateValidationRequest.php

  2. 在里面写下以下代码片段:

    use App'Http'Requests'Request;
    class StateValidationRequest 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()
    {
        return [
            'name' => 'Required|Regex:/^[a-zA-Z'(')'''.'s]+$/i|Max:100|Unique:loc_states,name,' . Request::segment(2) . ',_id',
            'country' => 'Required',
            'state_code' => 'alpha',
            'is_active' => 'Required|Boolean',
            'country_id' => 'Exists:loc_countries,_id',
            'revision' => 'numeric'
        ];
    }
    public function messages(){
        return [
            'name.required' => 'Name is required',
            'name.unique' => 'State name should be unique',
            'country.required' => 'Country is required',
            'state_code.alpha' => 'Code must be entirely alphabetic characters',
            'name.regex' => 'Allowed characters for name are a-z (lowercase and capital), brackets ''('' and '')'', single quote '', dot (.) and space ( )',
            'is_active.required' => 'State must be set to either active or in-active',
            'country_id.exists' => 'Kindly select a valid country',
            'revision.numeric' => 'Revision must be numeric'
        ];
     }
    }

  1. (最后)在控制器中(您想要验证的位置)

写下(在名称空间的顶部和下面):

use App'Http'Requests'Validator'StateValidationRequest;

并且,这在您的存储/更新功能中

public function store(StateValidationRequest $stateValidator){
}

如果存在任何类型的验证错误,它将重定向到注册页面。看看,如果有帮助的话。

嗨,你可以使用欧芹,例如,它是一个JS验证库。但也有其他的。我同意你的观点,每次你的用户填写字段时使用laravel验证器将是非常足智多谋的,所以在我看来不要这样做。

在某些情况下,进行JS验证非常有效,但实现起来可能更困难,也更耗时。如果您正在处理一个只有几个输入字段和简单验证规则的表单,那么进行JS验证是可以的,而且它可能对用户更友好。