define rules for multiple checkbox

Posted 8 months ago by [email protected]

Hi. i want to get and save information using a form . this form have multiple checkbox and i send form data using Ajax.but i cant not define proper rules for checkbox.i get all checkbox that are checked value and create a array and convert theme to string using

JSON.stringify

and send theme for controller But when none of them(checkboxes) Not checked the rule can not send error to form.

this is my form have multiple checkbox:

       <div class="row">

                @foreach($category as $cat)
                    <div class="col-md-3 custom-control custom-checkbox m-2">


                        <input class="custom-control-input" type="checkbox" name="category[]" id="{{$cat->name}}"
                               value="{{$cat->name}}">
                        <label for="{{$cat->name}}" class="custom-control-label">{{$cat->name}}</label>
                    </div>
                @endforeach
            </div>

I get checkbox value using jQuery set them inside a array and send them using Ajax and Json format But:

  

        $(document).ready(function () {



            $("input:submit").click(function (event) {

                event.preventDefault();
                $('#result').text("Processing...!!");
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    }
                });

                $.ajax({

                    url: "{{url('post/store')}}",
                    method: 'post',
                    dataType: 'json',
                    data: {

                        category:JSON.stringify(getCategory())
                    },
                    success: function (result) {
                        $("#result").text(result['saveState']);

                        $("#result").removeClass("alert-info  alert-danger ");
                        $("#result").addClass("alert alert-success");

                    },  //success
                    error: function (data) {

                      
                        var response = JSON.parse(data.responseText);

                        if (response.errors.category)
                            $("#result").append("<p>" + response.errors.category + "</p>");


                        $("#result").addClass("alert alert-danger")


                    }//error

                });

            });
//--------------------------------------------------


      /**
             * 
             * get checkbox that are selected value and create array
             */
            function getCategory() {


                var category = [];
                $("input[name='category[]']:checked").each(function () {
                    category.push($(this).val());
                })

                    return category;


            }//function category

//--------------------------------------------
        });


controller:


 public function rules()
    {
        return [
            'category' => 'required'

        ];
    }


 public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), $this->rules());
        if ($validator->fails()) {   // ||

            return response()->json(['errors' => $validator->getMessageBag()->toArray()], 400);
        }



            $post = new Post();
            $post->posts_id = rand(1, 10000);
            $post->title = $request->post_title;
            $post->body = $request->post_body;
            $data = json_encode($request->category);
            if ($post->save())
                return response()->json(['saveState' => 'Data is successfully added:']);
            else
                return response()->json(['saveState' => 'error in saving Data']);

    }



Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.