タイトル: 文字列の長さチェック
SEOタイトル: 文字列の長さチェック
この本文には実行可能なタグ等が含まれるため、安全のためHTMLソースとして表示しています。本文データは変更していません。
<table border="1" cellpadding="1" cellspacing="1" style="width:1000px">
<thead><tr><th style="background-color:#f39c12;color:#ffffff;text-align:left">この記事の要点</th></tr></thead>
<tbody><tr><td style="background-color:#fef9e7"><ul>
<li>Laravel で文字列長をチェックする方法</li>
<li>バリデーション: <code>'name' => 'required|min:3|max:100'</code></li>
<li><code>min:N</code> / <code>max:N</code>: 文字数指定(マルチバイト対応)</li>
<li>バイト数: <code>size:N</code></li>
<li>PHP 標準: <code>strlen()</code> (バイト) / <code>mb_strlen()</code> (文字)</li>
</ul></td></tr></tbody>
</table>
<p> </p>
<h2>Laravel バリデーション</h2>
<pre style="background:#0f172a;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;font-family:Consolas,Monaco,monospace;font-size:0.9em;line-height:1.5"><code>// FormRequest
public function rules()
{
return [
'name' => 'required|string|max:100', // 100 文字以内
'username' => 'required|min:3|max:30', // 3-30 文字
'description' => 'nullable|string|max:500',
'tag' => 'required|size:5', // ちょうど 5 文字
'phone' => 'required|regex:/^[0-9]{10,11}$/', // 10-11 桁の数字
];
}
// コントローラ
$request->validate([
'title' => 'required|max:200',
'content' => 'required|max:65535', // TEXT カラム
]);
// カスタムメッセージ
public function messages()
{
return [
'name.max' => '名前は :max 文字以内で入力してください',
'name.min' => '名前は :min 文字以上で入力してください',
];
}</code></pre>
<h2>主要バリデーションルール</h2>
<table border="1" cellpadding="1" cellspacing="1" style="width:1000px">
<thead><tr><th>ルール</th><th>意味</th></tr></thead>
<tbody>
<tr><td><code>min:N</code></td><td>最小 N 文字 (文字列) / 最小値 N (数値)</td></tr>
<tr><td><code>max:N</code></td><td>最大 N 文字 (文字列) / 最大値 N (数値)</td></tr>
<tr><td><code>size:N</code></td><td>ちょうど N 文字</td></tr>
<tr><td><code>between:min,max</code></td><td>min 〜 max 文字</td></tr>
<tr><td><code>digits:N</code></td><td>N 桁の数字</td></tr>
<tr><td><code>digits_between:min,max</code></td><td>min 〜 max 桁の数字</td></tr>
</tbody>
</table>
<h2>PHP 標準関数</h2>
<pre style="background:#0f172a;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;font-family:Consolas,Monaco,monospace;font-size:0.9em;line-height:1.5"><code><?php
// バイト数 (英数字なら文字数と同じ)
strlen("Hello"); // → 5
strlen("こんにちは"); // → 15 (UTF-8 で 3 バイト × 5)
// 文字数 (マルチバイト対応、推奨)
mb_strlen("Hello"); // → 5
mb_strlen("こんにちは"); // → 5
mb_strlen("こんにちは", "UTF-8");
// バイト数を mb_strlen でも取れる
mb_strlen($str, "8bit"); // → strlen と同じ
// よくある誤用
if (strlen($name) > 100) { ... } // ❌ 日本語だと予期しない結果
if (mb_strlen($name) > 100) { ... } // ✅ 正確に文字数</code></pre>
<h2>JavaScript での文字列長</h2>
<pre style="background:#0f172a;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;font-family:Consolas,Monaco,monospace;font-size:0.9em;line-height:1.5"><code>// length プロパティ (基本)
"Hello".length; // 5
"こんにちは".length; // 5 (UTF-16 コードユニット数)
"𝄞".length; // 2 (サロゲートペア)
// 正確な文字数 (Unicode コードポイント)
[..."𝄞"].length; // 1
Array.from("𝄞").length; // 1
// バイト数 (UTF-8)
new Blob([str]).size; // 正確な UTF-8 バイト数
new TextEncoder().encode(str).length; // 同上
// 実例
const text = "Hello, 世界! 🌍";
console.log(text.length); // 12
console.log([...text].length); // 11 (絵文字 1 つ)
console.log(new TextEncoder().encode(text).length); // 18 (UTF-8 バイト)</code></pre>
<h2>フロント側のリアルタイム文字数表示</h2>
<pre style="background:#0f172a;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;font-family:Consolas,Monaco,monospace;font-size:0.9em;line-height:1.5"><code><input type="text" id="title" maxlength="100">
<span id="count">0 / 100</span>
<script>
const input = document.getElementById("title");
const count = document.getElementById("count");
input.addEventListener("input", () => {
const len = [...input.value].length; // 正確な文字数
count.textContent = `${len} / 100`;
if (len >= 100) {
count.style.color = "red";
} else if (len >= 80) {
count.style.color = "orange";
} else {
count.style.color = "";
}
});
</script>
<!-- Vue.js -->
<template>
<input v-model="text" maxlength="100">
<span :class="{ 'text-danger': text.length >= 100 }">
{{ text.length }} / 100
</span>
</template></code></pre>
<h2>DB カラム制約</h2>
<pre style="background:#0f172a;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;font-family:Consolas,Monaco,monospace;font-size:0.9em;line-height:1.5"><code>-- VARCHAR(100): 最大 100 文字
CREATE TABLE users (
name VARCHAR(100) NOT NULL
);
-- CHECK 制約 (より厳密、PostgreSQL/SQL Server)
CREATE TABLE users (
name VARCHAR(100) NOT NULL CHECK (CHAR_LENGTH(name) >= 3)
);
-- MySQL でも 8+ で CHECK 制約サポート
CREATE TABLE users (
name VARCHAR(100) NOT NULL CHECK (CHAR_LENGTH(name) BETWEEN 3 AND 100)
);
-- 注意: VARCHAR は「文字数」、CHAR_LENGTH も「文字数」
-- LENGTH() はバイト数 (区別に注意)</code></pre>
<h2>UTF-8 ストレージサイズの理解</h2>
<table border="1" cellpadding="1" cellspacing="1" style="width:1000px">
<thead><tr><th>文字種</th><th>UTF-8 バイト数</th><th>例</th></tr></thead>
<tbody>
<tr><td>ASCII (英数字 / 記号)</td><td>1 バイト</td><td>A, 0, !</td></tr>
<tr><td>ラテン拡張 (アクセント文字等)</td><td>2 バイト</td><td>é, ñ</td></tr>
<tr><td>日本語・中国語・韓国語</td><td>3 バイト</td><td>あ, 漢, 한</td></tr>
<tr><td>絵文字・補助平面</td><td>4 バイト</td><td>😀, 🌍</td></tr>
</tbody>
</table>
<p>MySQL の utf8mb4 文字セット使用時、<code>VARCHAR(100)</code> = 最大 400 バイト。</p>
<h2>正規表現での検証</h2>
<pre style="background:#0f172a;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;font-family:Consolas,Monaco,monospace;font-size:0.9em;line-height:1.5"><code>// 半角英数字 5-20 文字
'username' => 'required|regex:/^[a-zA-Z0-9]{5,20}$/'
// 日本語 1-30 文字
'name' => 'required|regex:/^[ぁ-んァ-ヶ一-龯]{1,30}$/u'
// 電話番号 (ハイフン区切り or なし)
'phone' => 'required|regex:/^0\d{1,4}-?\d{1,4}-?\d{4}$/'
// 郵便番号
'zip' => 'required|regex:/^\d{3}-?\d{4}$/'</code></pre>
<h2>関連記事</h2>
<ul>
<li><a href="/article/21286">@RequestBody</a></li>
<li><a href="/article/20614">改行コードの削除</a></li>
<li><a href="/article/20614">文字列操作</a></li>
</ul>