マルチバイトの文字数チェックに対応するため、カスタムルールを作成した。
QuickForm2/Rule/Length.php の QuickForm2_Rule_Lengthを継承し、
validateOwner() の strlen を mb_strlen に変更するだけ。
QuickForm2/Rule/MbLength.php として保存。
class HTML_QuickForm2_Rule_MbLength extends HTML_QuickForm2_Rule_Length { /** * Validates the owner element * * @return bool whether length of the element's value is within allowed range */ protected function validateOwner() { if (0 == ($valueLength = mb_strlen($this->owner->getValue()))) { return true; } $allowedLength = $this->getConfig(); if (is_scalar($allowedLength)) { return $valueLength == $allowedLength; } else { return (empty($allowedLength['min']) || $valueLength >= $allowedLength['min']) && (empty($allowedLength['max']) || $valueLength <= $allowedLength['max']); } } }
QuickForm2/Factory.php に追記。
/** * List of registered rules * mblength, mbminlength, mbmaxlength: 2017.4 ushi add; * @var array */ protected static $registeredRules = array( 'nonempty' => array('HTML_QuickForm2_Rule_Nonempty', null), 'empty' => array('HTML_QuickForm2_Rule_Empty', null), //中略 'mblength' => array('HTML_QuickForm2_Rule_Length', null), 'mbminlength' => array('HTML_QuickForm2_Rule_MbLength', null, array('max' => 0)), 'mbmaxlength' => array('HTML_QuickForm2_Rule_MbLength', null, array('min' => 0)) );
PGでの使い方
//マルチバイト・文字数チェック $in_o_name->addRule('mbmaxlength', 'ご注文者 お名前:100文字までです',100); $in_message->addRule('mbmaxlength', 'メッセージ:1000文字までです',1000);