<script>
    // Add regex method to jQuery Validator
    $.validator.addMethod("regex", function(value, element, regexp) {
        var re = new RegExp(regexp);
        return this.optional(element) || re.test(value);
    }, "Le format est invalide.");

    //Create new promo form
    $('#submitFormPromo').on('click', function(e) {
        $('#formPromo').validate({
            rules: {
                libelle: {
                    required: true,
                    regex: "^(20\\d{2})/(20\\d{2})$"
                },

            },
            messages: {
                libelle: {
                    required: "Le champs est obligatoire!",
                    regex: "Le format est invalide.",
                },

            },
            submitHandler: function() {
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
                $.ajax({
                    url: "/newpromo",
                    type: "POST",
                    dataType: 'json',
                    beforeSend: function() {
                        $('#loader').removeClass('is-hidden')
                        $('*').css('pointer-events', 'none')
                    },
                    complete: function() { // Set our complete callback, adding the .hidden class and hiding the spinner.
                        $('#loader').addClass('is-hidden')
                        $('*').css('pointer-events', 'all')
                    },
                    data: {
                        libelle: $('#libelleId').val(),
                    },
                    success: function(response) {
                        window.location.replace('/accueil');

                    },
                    error: function(response) {
                        console.log(response);
                    }
                });
            }
        })
    });
</script>
