Contact Form 7で選択項目によって必須項目を切り替える方法

WordPressの人気フォームプラグイン「Contact Form 7(CF7)」では、
標準でフィールドを「必須」にすることができます。しかし、

  • 選択肢によって必須項目を切り替えたい
  • 特定の条件で入力フィールドを表示・非表示にしたい

といった動的な制御を行いたい場合、標準機能だけでは対応できません。

この記事では、Contact Form 7のラジオボタンの選択によって必須項目を動的に切り替える方法を詳しく解説します。

Contact Form 7で必須項目を切り替えたいケース

例えば、次のようなフォームを作成するとします。

[radio service use_label_element default:1 "同上" "上記以外"]
<div id="option2-field" class="conditional-field" style="display: none;">
    <ul>
        <li>
            <span class="title">郵便番号</span>[text zip2_kk id:zip2_kk class:p-postal-code]
        </li>
        <li>
            <span class="title">都道府県</span>[select addr2-city2_kk id:addr2-city2_kk class:p-region include_blank "東京都" "大阪府"]
        </li>
        <li>
            [text your-city2_kk2 id:your-city2_kk2 class:p-locality class:p-street-address placeholder "例)〇〇市〇〇町"]
            <br>[text your-adress3_kk3 id:your-adress3_kk3 placeholder "番地以下の住所を建物名込で記載ください"]
        </li>
        <li>
            <span class="title">請求書名</span>[text seikyu_name id:seikyu_name placeholder "例)株式会社 京典"]
        </li>
        <li>
            <span class="title">ご担当者名</span>[text seikyu_tanto id:seikyu_tanto placeholder "例)山田 太郎"]
        </li>
        <li>
            <span class="title">電話番号</span>[tel seikyu_tel id:seikyu_tel placeholder "例)00-0000-0000"]
        </li>
    </ul>
</div>

このフォームでは、「請求書送付先」のラジオボタンで「上記以外」を選んだ場合にのみ、住所入力欄を表示し、必須項目にしたいとします。

Contact Form 7で必須項目を動的に切り替える方法

Contact Form 7では、required 属性を動的に追加・削除するためにJavaScriptを使用する必要があります

問題点:CF7のバリデーションは後から追加したrequiredを認識しない

CF7は、フォームロード時のrequired状態をキャッシュしてしまうため、
後からJavaScriptで追加したrequiredを正しく認識しないことがあります。

解決策として、CF7が自動的に追加するnovalidate属性を削除し、
ブラウザの標準バリデーションを有効にすることで、この問題を回避できます。

JavaScriptで必須項目の切り替えを実装する

次のJavaScriptを追加することで、ラジオボタンの選択によって入力フィールドの表示・非表示と必須項目の追加・削除を切り替えることができます。

document.addEventListener("DOMContentLoaded", function() {
    const radioButtons = document.querySelectorAll('input[name="service"]');
    const option2Field = document.querySelector("#option2-field");
    const form = document.querySelector("form"); // Contact Form 7のフォームを取得

    // 必須項目にする対象のフィールド
    const requiredFields = [
        document.getElementById("zip2_kk"),
        document.getElementById("addr2-city2_kk"),
        document.getElementById("your-city2_kk2"),
        document.getElementById("your-adress3_kk3"),
        document.getElementById("seikyu_name"),
        document.getElementById("seikyu_tanto"),
        document.getElementById("seikyu_tel")
    ];

    function updateVisibility() {
        const selectedValue = document.querySelector('input[name="service"]:checked');

        if (selectedValue && selectedValue.value === "上記以外") {
            option2Field.style.display = "block";
            requiredFields.forEach(field => {
                if (field) {
                    field.setAttribute("required", "required");
                    console.log("必須追加: ", field.id);
                }
            });
        } else {
            option2Field.style.display = "none";
            requiredFields.forEach(field => {
                if (field) {
                    field.removeAttribute("required");
                    console.log("必須解除: ", field.id);
                }
            });
        }
    }

    // ラジオボタンの変更イベントを監視
    radioButtons.forEach(radio => {
        radio.addEventListener("change", updateVisibility);
    });

    // CF7の `novalidate` を削除(ブラウザの標準バリデーションを有効化)
    if (form) {
        form.removeAttribute("novalidate");
        console.log("novalidate 属性を削除しました");
    }

    // 初期状態のチェック
    updateVisibility();
});

まとめ

Contact Form 7のrequiredはJavaScriptで動的に切り替え可能
novalidateを削除してブラウザのバリデーションを有効化
requiredの追加・削除をラジオボタンの変更イベントで制御

これで、Contact Form 7を使ったフォームでも
「選択肢によって必須項目を動的に切り替える」ことができるようになります!

ぜひ試してみてください!