contactform7にbootstrap4のカスタムバリデーションスタイルを適用する方法

前提

バリデーションを行って、boostrap4のカスタムバリデーションスタイルを適用したい。

参考リンク
https://getbootstrap.com/docs/4.3/components/forms/#custom-styles

上記を参考にして、以下を追加して送信しても、必須項目が入力されていない状態でvalidになってしまう。

<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
</script>

contactform7では必須項目でもrequired属性が付与されないので、以下の1行をスクリプトに追加してあげる。

$('.wpcf7-validates-as-required').attr('required', true);