laravel ajax验证未显示所有字段

时间:2014-05-10 07:10:50

标签: javascript php ajax laravel

我正在使用jquery ajax验证。问题是只有表格的某些字段才会显示验证,而其他字段则不显示。

jQuery(document).ready(function()
{
    jQuery('form#inline-validate').submit(function()
    {       
        jQuery.ajax({
            url: "http://localhost:8080/insur_docs/store",
            type: "post",
            data: jQuery('form#inline-validate').serialize(),
            datatype: "json",
            beforeSend: function()
            {
                jQuery('#ajax-loading').show();
                jQuery(".validation-error-inline").hide();
            }
            })
            .done(function(data)
            {
                if (data.validation_failed === 1)
                {
                    var arr = data.errors;
                    jQuery.each(arr, function(index, value)
                    {
                        if (value.length !== 0)
                        {
                            jQuery("#" + index).after('<span class="text-error validation-error-inline">' + value + '</span>');
                        }
                    });
                    jQuery('#ajax-loading').hide();
                }
            })
            .fail(function(jqXHR, ajaxOptions, thrownError)
            {
                  alert('No response from server');
            });
            return false;
    });
});

insur_docs_controller.blade.php

<div id="div-1" class="body">
            {{ Form::open(array('url' => 'insur_docs/store', 'class'=>'form-horizontal','id'=>'inline-validate')) }} 
            <div class="form-group">
                {{ Form::label('ownership_cert', 'Ownership Certificate*', array('class'=>'control-label col-lg-4')) }}
                <div class="col-lg-8">
                    {{ Form::select('ownership_cert', array('' => '', '1' => 'Yes', '0' => 'No'),Input::old('ownership_cert'),  array(
                                'class' => 'form-control'))
                    }}

                </div>
            </div>
            <div class="form-group">
                {{ Form::label('authoriz', 'Authorization*', array('class'=>'control-label col-lg-4')) }}            
                <div class="col-lg-8">
                    {{ Helpers\Helper::date('authoriz', Input::old('authoriz') , array(
                                'class' => 'form-control')) 
                    }}

                </div>
            </div>
            <div class="form-group">
                {{ Form::label('drive_permis', 'Drive Permission*', array('class'=>'control-label col-lg-4')) }}
                <div class="col-lg-8">
                    {{ Form::select('drive_permis', array('' => '', '1' => 'Active', '0' => 'Not active'),  Input::old('drive_permis'),  array(
                                'class' => 'form-control'))
                    }}

                </div>
            </div>
            <div class="form-group">
                {{ Form::label('sgs', 'SGS*', array('class'=>'control-label col-lg-4')) }}
                <div class="col-lg-8">
                    {{ Helpers\Helper::date('sgs',  Input::old('sgs') , array(
                                'class' => 'form-control')) 
                    }}

                </div>
            </div>  
            <div class="form-group">
                {{ Form::label('tpl', 'TPL*', array('class'=>'control-label col-lg-4')) }}
                <div class="col-lg-8">
                    {{ Helpers\Helper::date('tpl', Input::old('tpl') , array(
                                'class' => 'form-control')) 
                    }}

                </div>
            </div>
            <div class="form-group">
                {{ Form::label('kasko', 'Kasko*', array('class'=>'control-label col-lg-4')) }}
                <div class="col-lg-8">
                    {{ Helpers\Helper::date('kasko', Input::old('kasko') , array(
                                'class' => 'form-control')) 
                    }}

                </div>
            </div>
            <div class="form-group">
                {{ Form::label('inter_permis', 'International Permission*', array('class'=>'control-label col-lg-4')) }}
                <div class="col-lg-8">
                    {{ Helpers\Helper::date('inter_permis', Input::old('inter_permis') , array(
                                'class' => 'form-control')) 
                    }}

                </div>
            </div>
            <div class="form-group">
                {{ Form::label('car', 'Car*', array('class'=>'control-label col-lg-4')) }}
                <div class="col-lg-8">
                    {{ Form::select('car', $cars, Input::old('car'), array( 
                                'data-validation-error-msg' => 'You did not enter a valid car',
                                'class' => 'form-control')) 
                    }}<br/>
                    @if($errors->count() > 0)
                    <div class="alert alert-danger">
                        <p>The following errors have occurred:</p><br/>
                        @foreach($errors->all() as $message)
                        {{ Helpers\Helper::macro($message) }}<br/>
                        @endforeach
                    </div>
                    @endif                
                </div>
            </div>  

            {{ Form::submit('Save', array('class' => 'btn btn-success btn-line')) }}
            <input type="button" value="Back" class="btn btn-danger btn-line" onClick="history.go(-1);
                    return true;">
            {{ Form::close() }}
            {{ HTML::script('assets/js/jquery.validate-form.js') }}
        </div>

因此验证仅针对ownership_cert和drive permis显示。对于其他领域没有。我创建了一个日期函数:

  public static function date($name, $value = null, $options = array()) {
        $input = '<input type="date" name="' . $name . '" value="' . $value . '"';

        foreach ($options as $key => $value) {
            $input .= ' ' . $key . '="' . $value . '"';
        }

        $input .= '>';

        return $input;
    }

问题可能与此有关吗?

2 个答案:

答案 0 :(得分:0)

试试这个:

jQuery(document).ready(function()
{
    jQuery('form').submit(function()
    {
        var url = $(this).attr("action");
        jQuery.ajax({
            url: url,
            type: "post",
            data: jQuery('form').serialize(),
            datatype: "json",
            beforeSend: function()
            {
                jQuery('#ajax-loading').show();
                jQuery(".validation-error-inline").hide();
            }
        })
                .done(function(data)
                {
                    $('#validation-div').empty()
                    if (data.validation_failed === 1)
                    {
                        var arr = data.errors;
                        jQuery.each(arr, function(index, value)
                        {
                            if (value.length !== 0)
                            {
                                $("#validation-div").addClass('alert alert-danger');
                                document.getElementById("validation-div").innerHTML += '<span class="glyphicon glyphicon-warning-sign"></span>' + value + '<br/>';
                            }
                        });
                        jQuery('#ajax-loading').hide();
                    }
                    else {
                        window.location = data.redirect_to;
                    }
                })
                .fail(function(jqXHR, ajaxOptions, thrownError)
                {
                    alert('No response from server');
                });
        return false;
    });
});

答案 1 :(得分:0)

我在项目中应用了以下解决方案,并且工作正常。 请检查。

您需要在控制器中添加以下代码。

$validator = Validator::make($input, $rules, $messages);
if ($validator->fails()) {
    $errors = $validator->errors()->getMessages();
    $arr = array("status" => 400, "msg" => $errors, "result" => array());
}

$ errors = $ validator-> errors()-> getMessages(); getMessages();函数将为您提供所有错误消息,并带有您输入名称的键。 通过使用输入名称键,您可以在输入下方打印特定的错误消息。

index.blade.php

        <div class="form-group m-form__group">
            <label>
                Name<span class="text text-danger">*</span>
            </label>
            <input type="text" class="form-control m-input" name="name"  placeholder="Enter user name" @if(isset($data)) value="{{$data->name}}"  @endif />
            <span class="error_msg" id="error_name"></span>
        </div>

        <div class="form-group m-form__group">
            <label>
                Email<span class="text text-danger">*</span>
            </label>
            <input type="email" class="form-control m-input" name="email" placeholder="Enter email" @if(isset($data)) value="{{$data->email}}"  @endif />
            <span class="error_msg" id="error_email"></span>
        </div>

您的custom.js文件

$.ajax({
                type: "POST",
                url: url,
                data: fdata,
                headers: {
                    'X_CSRF_TOKEN': '{{ csrf_token() }}',
                },
                contentType: false,
                processData: false,
                "success":function (data) {

                    var message = data.msg;

                    jQuery.each(message, function(key, value){
                        jQuery('#error_'+key).html(value[0]);
                    });
                   },

                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Something went wrong. Please try again.");
                    //unload();
                }
            });