1

我需要对标签输入使用 laravel 唯一验证,但我面临多个值的问题,插入一个值时唯一规则运行良好,但添加多个值时它不起作用。

这是我的控制器代码

 public function createteacher()
 {
     $rules = array (
         'teacher-name'  => 'required|unique:teacher,name',
     );

     $msgs =array(
         'teacher-name.required' => 'please insert teacher name',  
         'unique' => 'teacher name already exist',
     );

     $validator = Validator::make(Input::all(),$rules,$msgs);

     if ($validator->fails())
     {
         return  Response::json(['success'=>false,'error'=>$validator->errors()->toArray() ]);
     }
     else
     {
         $c = count(explode(',', Input::get('teacher-name')));

         $teachers_ids = explode(',', Input::get('teacher-name'));

         //if Validated
         for ($i = 0 ; $i < $c ; $i++)
         {
             $new_teacher = Teacher::firstOrCreate(array('name'=>$teachers_ids[$i]));  
         }

         return Response::json(['success'=>true]); 
     }
 }

这是我的视图代码

<div class="col-md-6">
 <div class="box box-redorange">
  <div class="box-header">
   <h3 class="box-title" style="float:right"> Adding Teachers </h3>
  <i class="fa fa-spinner fa-spin fa-lg" style="display:none float:left;" id="teacher-adding-load"></i> &nbsp;
   </div>
  <div class="box-body">                                    

     {{Form::open(array('url'=>'management/createteacher','id'=>'teacher-form'))}}
   <div class="form-group">
    <label for="teacher-name[]">Teacher Name </label>
    <select multiple data-role="tagsinput" name="teacher-name[]"   id="teacher-name" class="form-control" autofocus="true">
           <option value="" ></option>
    </select>
      </div>                     
      </div> <!-- end box body-->
      <div class="box-footer">
      {{Form::submit('Add',array('style'=>'color:#fff;font-weight:bold; ','class' => 'btn btn-redorange btn-block btn-sm')) }}
       {{Form::close()}}
       </div> <!--end box footer -->
       </div> <!-- end box -->
       <div class="form-group help-block teahcer-form-msgs" style="display:none;">
             <small></small>
       </div> 
      </div> <!-- end col-m-6 -->

最后是我的ajax代码

 $(document).ready(function(){

 var msgs = $('.teahcer-form-msgs');

 $('#teacher-form').submit(function(e){
  e.preventDefault();
 var $teacher_loading = $('#teacher-adding-load').show();

   // form data
    var formData = new FormData ();

     formData.append('teacher-name' , $('#teacher-name').val());

 $.ajax({
 url:'/elaqsacenter/public/management/createteacher',
 method:'post',
 processData:false,
 contentType:false,
 cache:false,
 dataType: 'json',
 data:formData,
 complete:  function(){
      $teacher_loading.hide();
  },
   global: false,
   success:function(data){

   msgs.hide().find('small').empty();

   if (!data.success) {

    $.each(data.error,function(index,error){

        msgs.find('small').append('<p class="text-danger">'+'<span     

       class="glyphicon glyphicon-exclamation-sign" aria-hidden="true">

       </span>'+' '+error+'</p>');

      // disable submit button when throw Validation messages 
     $('input[type=submit]').prop("disabled", true);
       setTimeout(function() {
       $('input[type=submit]').prop("disabled", false);
      }, 4000);
  });
    msgs.slideDown();
    msgs.delay(3000).slideUp();

  }else{
 msgs.find('small').append('<p class="text-success">data Inserted</p>');
      msgs.slideDown();
      msgs.delay(3000).slideUp();
      setTimeout(function(){location.reload();},2000);  
   }

 },
  global: false,
  error:function(){},

   });

  });

});

我的主要问题是如何使用通过标签输入插入多个值的唯一规则

4

2 回答 2

1

我有同样的问题。问题是您正在提交一个数组 [] teacher-name[]。鉴于此,假设在提交后您可以通过键入以下内容输出您拥有的整个数组:

$data=Input::all();
            echo '<p style="color: blue;">The array data submitted are :<br><strong>'.print_r(Input::all(),true).'</strong></p>';
            die();

你会注意到你实际上是在一个数组中得到一个数组。所以验证需要一个值数组,而不是数组数组。

要解决这个问题,您需要使用 foreach 函数。仅出于测试目的,假设老师的姓名长度不应超过 5 个字符:

    $data=Input::all();
                echo '<p style="color: blue;">The array data submitted are :<br><strong>'.print_r(Input::all(),true).'</strong></p>';
foreach ($data['teacher-name'] as $key => $value) {
$validacion=Validator::make(
                        array(
                            $key    =>  $value
                            ),
                        array(
                            $key    =>  'max:5'
                            ),
                        array(
                            'max'   => 'In Spanish i\'d say this field can\'t be greater than :max chars...'
                            )
                        );
                    if($validacion->fails()){
                        echo '<p style="color: red;">Validation has failed for <b>'.$value.'</b></p>';
                    }
}
            die();

因此,解决方案是在提交数组数组时必须使用 foreach 函数Input::all()

于 2015-05-19T15:48:22.887 回答
0

我发现更简单的方法可以遍历 tagsInput 值来验证它,如下所示

   $c = count(Input::get('teacher-name') );

    //In view the name must be  name="teacher-name[]"
   $teacher_name =Input::get('teacher-name');

   /* To loop over multiple values that insert from tags input.
      you can add all laravel validation with this way .
      and custom :attribute by setAttributeNames() method */      
    for ($i = 0; $i < $c ; $i++){

   $rules[$i] = 'required|between:3,15';

   $customAttributes[$i] =  $i + 1  ;
}

    $msgs =  array('required' => '.Teacher Name Is Required' ,
                   'between' => '.Teacher Num  (:attribute) must be between 3 : 15 chars' ) ; 

    $validateTeacher = Validator::make($teacher-name,$rules,$msgs);
    $validateTeacher->setAttributeNames($customAttributes); 

      if ($validateDivision->fails() OR $validateGrade->fails()) 
    {
       // return Ajax Validation Messages OR laravel Validation Messages 
    }

通过上述方式,您可以一个一个地循环标记输入值,享受:)

于 2015-05-20T07:59:27.163 回答