PowerCMSの編集画面でUTF8の4バイト文字入力を検知する
今後の案件で要件としてちょこちょこ出そうなのでメモ。
例えば記事の編集画面でUTF8の4バイト文字(絵文字など)の入力があると、CMSのDBの設定によっては上手く保存されない場合がある。この為、案件の要件として、UTF8の4バイト文字を入力させないようにしてほしい、という話が出る時がある。
今回は、それに対応する為、記事の編集画面で保存時に4バイト文字を検出して例外表示を出すロジックのサンプルを示す。
使い方として、CMS管理画面の対象ウェブサイト/ブログの設定>PowerCMSの設定画面の入力項目「管理画面カスタマイズ設定」に、次のサンプルコードを入力・保存する。
<mt:if name="request.__mode" eq="view">
<mt:if name="request._type" eq="entry">
<mt:ignore>「記事の編集」画面</mt:ignore>
<mt:ignore>入力バリデーション</mt:ignore>
<script>
jQuery(function($){
$('input[type="submit"].action, button[type="submit"].action')
.filter(".publish")
.on("click", function() {
console.log('pressd publish-button.');
var ret = true;
var str__fldblk_errmsg = "";
let str__target_selector = '#sortable #editor-input-content_ifr,'
+ '#sortable #editor-input-extended_ifr,'
+ '#sortable input[id^="customfield_"][type="text"],'
+ '#sortable textarea[id^="customfield_"]';
$(str__target_selector).each(function(){
let jq__target, str__target, label__target;
if ( $(this).attr("id") === 'editor-input-content_ifr' ){
let jq__content = $('#text-field #editor-input-content_ifr').contents();
jq__target = jq__content.find('#editor-input-content.mce-content-body').eq(0);
str__target = jq__target.html();
label__target = "本文";
}
else if ( $(this).attr("id") === 'editor-input-extended_ifr' ){
let jq__content = $('#text-field #editor-input-extended_ifr').contents();
jq__target = jq__content.find('#editor-input-extended.mce-content-body').eq(0);
str__target = jq__target.html();
label__target = "続き";
}
else {
jq__target = $(this);
str__target = jq__target.val();
label__target = jq__target.closest('.field-top-label').children('.field-header').eq(0).children('label').eq(0).text();
}
const r = str__target.replace(/^\s*[\r\n]+/gm, '');
for (var i = 0; i < r.length; i++) {
try {
encodeURIComponent(r.charAt(i));
}
catch(e) {
try {
encodeURIComponent(r.substring(i, i + 2).charAt(1));
}
catch (e) {
str__fldblk_errmsg +=
label__target + ' : '
+ `4バイト文字の「${r.substring(i, i + 2)}」が含まれています。\r\n`;
}
}
}
});
if ( str__fldblk_errmsg.length > 0 ){
alert( str__fldblk_errmsg );
ret = false;
}
else{
ret = window.confirm('保存を実行しますか?');
}
return ret;
});
});
</script>
<mt:ignore>/入力バリデーション</mt:ignore>
<mt:ignore>/「記事の編集」画面</mt:ignore>
</mt:if>
</mt:if>
これで、記事の編集画面の本文、続き、およびカスタムフィールドの一行テキスト/テキストエリアが4バイト文字検知の対象となり、「保存(更新)」ボタン押下時に検知のロジックが走って、検知されると例外表示が出る。
検知の仕組みとしては、JSのencodeURIComponentで4バイト文字を変換しようとするとエラーになる事を利用して、検知している。
参考
UTF-8の4バイト文字のバリデーション - Pistolfly
Webページ内に4バイト文字が含まれるかJavaSctiptで調べる方法 | iwb.jp