Skip to content
Advertisement

laravel validation system stop the insertion even the field is hidden by jQuery

in a form I have a select category which allows you to hide or show the inputs according to type to select in select category. this form is to insert an advertisement either title or name use validation system, when I click on button insertion, validation system check other value even it is hidden by jQuery, then it stops the insertion how solved this problem.

create.blade.php

<div class="form-group">
  <label>Categories <span class="text-hightlight">*</span></label>
  <select class="form-control" name="category_id" id="category_id">
    <option>select</option>
    <option value="1">titre</option>
    <option value="2">name</option>
  </select>
</div>
<div class="form-group" id="divt">
  <label>titre <span class="text-hightlight">*</span></label>
  <input type="text" name="titre" class="form-control"/>
</div>
<div class="form-group" id="divn">
  <label>name <span class="text-hightlight">*</span></label>
  <input type="text" name="name" id="name" class="form-control"/>
</div>

jQuery

<script>
  $(document).on('change', '#category_id', function() {
    var stateID = $(this).val();
    alert(stateID);
    if (stateID == '1') {
      $("#divn").hide();
      $("#divt").show();
    } else if(stateID == '2') {
      $("#divt").hide();
      $("#divn").show();
    }   
  });  
</script>

AdsController.php

public function store(Request $request) {
  $this->validate($request, [
    'titre' => ['bail','required', 'string','min:3', 'max:255'],
    'name' => ['bail','required', 'string','min:3', 'max:255'],
  ]);

  $ads= new Ads($request->all());
  $ads->save();
        
  return Redirect::to("/")
  ->withSuccess('Great! file has been successfully uploaded.');
}

Advertisement

Answer

Hiding elements via CSS doesn’t remove them from the DOM. So the fields will be submitted even if they aren’t visible.

Try something like this instead:

public function store(Request $request)
{
    $this->validate($request, [
        'field' => ['bail', 'required', 'in:1,2'],
        'titre' => ['bail', 'required_without:name', 'string','min:3', 'max:255'],
        'name' => ['bail', 'required_without:titre', 'string','min:3', 'max:255'],
    ]);

    Ads::create($request->all());

    return Redirect::to("/")
        ->withSuccess('Great! file has been successfully uploaded.');
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement