フォームの必須エラーメッセージをHTML5標準にする方法、カスタマイズする方法

CakePHP4以降ではフォームのinputがrequiredの場合、ブランクで送信しようとすると「This field cannot be left empty」メッセージが表示されます。


HTML5標準ではブラウザ側の機能で、各言語に合わせたメッセージが表示されます。
日本語設定のGoogle Chromeでは、「このフィールドを入力してください。」となります。


CakePHPのメッセージではなく、HTML5のメッセージを表示するようにする方法の説明です。
ページごとの記述方法
サイト全体の記述方法
メッセージをカスタマイズする方法

この設定は、FormHelperの設定値「autoSetCustomValidity」です。
trueであればCakePHPのメッセージ、falseであればHTML5のメッセージが表示されます。

CakePHP3から実装され、CakePHP3ではデフォルト値がfalse、CakePHP4以降ではtrueになっています。

trueの場合

<input type="text" name="name" required="required" data-validity-message="This field cannot be left empty" oninvalid="this.setCustomValidity(''); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)" oninput="this.setCustomValidity('')" id="name" aria-required="true">

falseの場合

<input type="text" name="name" required="required" id="name" aria-required="true">

ページごとの記述方法

ページごとに変更するには、ページのテンプレートファイルに下記を記述します。

$this->Form->setConfig('autoSetCustomValidity', false);

サイト全体の記述方法

サイト全体で変更するには、カスタムヘルパーに記述します。
[参考記事] 標準のHelperを拡張してカスタマイズする方法 CakePHP3、CakePHP4

ヘルパー全体での指定は initialize() に下記を記述します。

$this->setConfig('autoSetCustomValidity', false);


src/View/Helper/CustomFormHelper.php

<?php
declare(strict_types=1);

namespace App\View\Helper;

use Cake\View\Helper\FormHelper;

/**
 * FormHelperの拡張ヘルパー
 *
 * @property \Cake\View\Helper\HtmlHelper $Html
 * @property \Cake\View\Helper\UrlHelper $Url
 * @link https://book.cakephp.org/4/ja/views/helpers/form.html
 */
class CustomFormHelper extends FormHelper
{
    /**
     * Constructor hook method.
     *
     * @param array<string, mixed> $config The configuration settings provided to this helper.
     * @return void
     */
    public function initialize(array $config): void
    {
        parent::initialize($config);

        // HTML5メッセージをカスタムしない
        $this->setConfig('autoSetCustomValidity', false);
    }
}

__construct() でも書けますが、CakePHP準拠の記法は initialize() です。

    public function __construct(View $view, array $config = [])
    {
        parent::__construct($view, $config);

        // HTML5メッセージをカスタムしない
        $this->setConfig('autoSetCustomValidity', false);
    }

メッセージをカスタマイズする方法

CakePHPのメッセージ文言はi18nで制御されています。
国際化i18n(多言語化)

バリデーションエラーの文言は下記です。

#: ./vendor/cakephp/cakephp/src/Validation/Validator.php:2570
msgid "This field is required"
msgstr ""

#: ./vendor/cakephp/cakephp/src/Validation/Validator.php:2590
#: ./vendor/cakephp/cakephp/src/View/Form/ArrayContext.php:251
msgid "This field cannot be left empty"
msgstr ""

#: ./vendor/cakephp/cakephp/src/Validation/Validator.php:2742
msgid "The provided value is invalid"
msgstr ""

/resources/locales/ja_JP/cake.po

msgid "This field is required"
msgstr "この項目は必須です"

msgid "This field cannot be left empty"
msgstr "このフィールドを空のままにすることはできません"

msgid "The provided value is invalid"
msgstr "指定された値は無効です"

関連記事

スポンサーリンク

ANY演算子 『いずれか』を表す比較演算子の修飾子

ホームページ製作・web系アプリ系の製作案件募集中です。

上に戻る