如何在空帖子时验证字段 - Ajax,Laravel

时间:2017-06-21 06:39:45

标签: php jquery laravel laravel-5 laravel-5.4

我使用Laravel Blade中的Ajax将数据发布到Controller。我为此表单添加了Jquery验证,当提交按钮时单击其转到相应的路由和显示错误。如何验证这种类型的字段。

$(document).ready(function() {  

 $("#add").click(function(event) {

      if( !$('#ledger_name').val() ) {
          $('#ledger_name').parents('p').addClass('warning');
       }

     event.preventDefault();

        $.ajax({
            type: 'post',
            url: $("#add").attr('data-url'),
            data: {
             '_token': '{{ csrf_token() }}',
            'form_data': $('#Form').serialize(),
            },
            success: function(data) {

                 $('#ledger_name').val('');
                 $('#openning_balance').val('0.00');
                 $('#ob_type').val('');
                 $('#under').val('');
                 $('#ledger_address').val('');
                 $("#newLedger .close").click();
                 $(".result").html(data.success).css({'color': 'green', 'text-align': 'center'}).delay(5000).fadeOut();
            },

         error: function(data)
            {
                var errors = '';
                for(datos in data.responseJSON){
                    errors += data.responseJSON[datos] + '<br>';
                }
                $('#response').show().html(errors); //this is my div with messages
            }

        });

    });

    });

控制器代码:

public function addnewledgers(Request $request){

    $usersid = Auth::user()->id;
    $companyids = Session()->get('companyids'); 

    $values = array();
    parse_str($_POST['form_data'], $values);

    $insertledgers=Ledger::create(['ledger_name'=>$values['ledger_name'],'openning_balance'=>$values['openning_balance'],'ob_type'=>$values['ob_type'],'under'=>$values['under'],'ledger_address'=>$values['ledger_address'],'company_id'=>$companyids,'user_id'=>$usersid,'created_by'=>$usersid]);

    return response()->json(['success' => 'Ledger Details Added Successfully',]);   

    }

1 个答案:

答案 0 :(得分:2)

您可以创建如下所示的验证器函数,并将验证消息发送到数组。

protected function validator(array $data )
{
    return Validator::make($data, [
        'name' => 'required|string|max:255|unique:users',
    ]);
}

并将控制器方法中的验证函数称为。

$validation = $this->validator($request->all(),true );
if($validation->fails()){
    $errors = $validation->errors();
    return response()->json(
        ['errors' => $errors, 'status' => 'error'],200
    );
}

您可以按以下方式更改方法。 (建议使用$ request而不是$ _POST)

public function addnewledgers(Request $request){

    $usersid = Auth::user()->id;
    $companyids = Session()->get('companyids');

    Validator::make( $request->all(), [
            'ledger_name' => 'required',
            //other validations
    ]); 

    if($validation->fails()){
        $errors = $validation->errors();
        return response()->json(
            ['errors' => $errors, 'status' => 'error'],200
        );
    }   


    $values = array();
    parse_str($_POST['form_data'], $values);

    $insertledgers=Ledger::create(['ledger_name'=>$values['ledger_name'],'openning_balance'=>$values['openning_balance'],'ob_type'=>$values['ob_type'],'under'=>$values['under'],'ledger_address'=>$values['ledger_address'],'company_id'=>$companyids,'user_id'=>$usersid,'created_by'=>$usersid]);

    return response()->json(['success' => 'Ledger Details Added Successfully',]);   

}