Laravel使用请求验证传入的ajax

时间:2017-08-09 08:17:12

标签: ajax laravel laravel-5

我有这样的观点:

//视频片段

<td><input class="form-field" type="text" id="entity" name="name" data="{{$entity->id}}" value="{{$entity->name}}" onkeyup="validation(this.value);" onblur="updateEntity(this.value,this.name,this.id,{{$entity->id}})"></td>

<td><input class="form-field" type="text" id="entity" name="type" value="{{$entity->type}}" onkeyup="validation(this.value);" onblur="updateEntity(this.value,this.name,this.id,{{$entity->id}})"></td>

哪个有ajax:

function updateEntity(value, name, data, id) {
  $.ajax({
        url: '/entityadmin/' + value + '/' + name + '/' + data + '/' + id,
        method: 'POST',
        dataType: 'json',
        success: function(save) {
          $('.messages').append('<div class="alert alert-success">Type Updated!<div>');
            setTimeout(function() {
              $(".alert").fadeTo(2000, 500).slideUp(500, function(){
                $(".alert").slideUp(500);
              });  
            }, 4000); 
        },
        error: function(data) {
          console.log(data);
          $('.messages').append('<div class="alert alert-danger">Error, please try again!<div>');
            setTimeout(function() {
              $(".alert").fadeTo(2000, 500).slideUp(500, function(){
                $(".alert").slideUp(500);
              });  
            }, 4000); 
        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
}

控制器:

public function entityUpdate($value, $name, $data, $id, EntityRequestUpdate $request) {

        $request->$name = $value; //like this?
        if($data == "entity") {
            $save = Entity::find($id);
        }else{
            $save = User::find($id);
        }
        $save->$name = $value;
        $save->save();
        return response()->json(['results' => $save]);       
    }

并请求:

public function rules()
    {
        return [
            'startdate' => 'required|date',
            'endate' => 'nullable|date',
            'startime' => 'required|time',
            'endtime' => 'required|time',
            'title' => 'required',
            'type' => 'required',
            'description' => 'required',
            'frequency' => 'required',
            'interval' => 'nullable|numeric',
            'monthday' => 'nullable|numeric|min:1|max:3',
            'weekday' => 'nullable|alpha|max:3',
            'month' => 'nullable|numeric',
            'until' => 'nullable|date',
            'tags' => 'nullable',
            'img' => 'nullable|file|image',
        ];
    }

问题是它只需要验证一个字段,因为每次都要更改一个字段,我如何使用此验证来验证传入变量并将错误返回给ajax,如果有错误消息?< / p>

1 个答案:

答案 0 :(得分:0)

您可以manually create a validator验证这一个字段,如下所示:

$validator = Validator::make(
    [ 'name' => $value ], 
    collect($this->rules())->only([$name])->all()
);

此验证器将从定义的规则中获取name验证器,并针对第一个值数组进行检查。