Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

各ブラウザがmaxlengthを指定したテキストボックスにサロゲートペアの文字を何文字入力できるか

<input type="text" maxlength="5">に対して、各文字をペーストしつづけてみた。

𩸽 か゚
Chrome on Windows11 あああああ 𩸽𩸽 か゚か゚か
Edge on Windows11 あああああ 𩸽𩸽 か゚か゚か
Edge IE mode on Windows11 あああああ 𩸽𩸽𩸽𩸽𩸽 か゚か゚か
Firefox on Windows11 あああああ 𩸽𩸽 か゚か゚か
Safari on macOS 11 あああああ 𩸽𩸽𩸽𩸽𩸽 か゚か゚か゚か゚か゚
Safari on iOS 14.8 あああああ 𩸽𩸽𩸽𩸽𩸽 か゚か゚か゚か゚か゚

では、結局どの挙動が仕様に照らして正しいのか?

WHATWG HTML Living Standardの2021/12/21版では、maxlength属性を持つコントロールは、その値の長さ(length)がmaxlength以下でなくてはならないとされている*1。ここで文字列の長さ(length)とは、その文字列に含まれるコードユニット(code units)の数*2であると定義されている。ここで、文字列はコードユニットの列であり、コードユニットとは16bit符号なし整数のこととされている*3。コードユニットはUnicodeのコードポイントとは独立して定義されているので、コードポイントのことではない。

つまり、WHATWG HTML Living Standardに照らすと、各ブラウザの結果は以下のように解釈できる。

  • Chrome・Edge・FirefoxWHATWGの仕様通りにmaxlengthを実装している。
  • IEおよびEdgeのIEモードでは「コードユニット」と「コードポイント」を取り違えている。
  • Safariは「値の長さ(length)」を書記素(grapheme)の数と独自に解釈している。コードユニットだのコードポイントだのユーザにとっては知ったこっちゃないから、ある意味ユーザのことを考えているとも言える。

*1:If the input element has a maximum allowed value length, then the length of the value of the element's value attribute must be equal to or less than the element's maximum allowed value length.

*2:https://infra.spec.whatwg.org/#string-length

*3:A string is a sequence of unsigned 16-bit integers, also known as code units. A string is also known as a JavaScript string.