1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

またまた Hibernate Validator でコケたメモ - @NotBlank編 -

Posted at

@​NotBlank is 何

null, 空文字に加えて「スペースのみ」も弾くバリデーション。

なんでコケたの?

あいつ半角スペースしか見てねえ

どういうこと?

どうやら @​NotBlank のバリデータ、実装に String#trim() を使っている様子。
String#trim() は両端から見てスペースを詰めていき String#substring(int, int) で中身だけ切り離して返すものだが、この時ベタ打ち char の半角スペースを基準に、それ以下のコードのものを全て詰めるという実装である。
つまり全角スペースは通す。死ぬ。

どうすればいいの?

Apache Commons 使おう。みんな大好き StringUtils だ (前もこんなんじゃなかったか?) 。

StringUtils.isBlank(CharSequence) (lang3 の方だぞ!) の Javadoc には whitespace の定義として Character.isWhitespace(char) を使用していると明記されている。
Character.isWhitespace(char) は改行やタブ等に加え、スペースとされるものの定義に Unicode の SEPARATOR 三種 (SPACE_SEPARATOR, LINE_SEPARATOR, PARAGRAPH_SEPARATOR - ただし、ノンブレークスペースは除外されている) を使っている。大抵のものは弾いてくれるはずだ。

同様の理由で、 trim したくなったときも StringUtils.strip を使ったほうが安全なことがある1

でも Commons って Annotation あったっけ?

ない。さっくり書こう。
前もやったので、もしも必要なら@​Email の時の記事を参照してほしい。2

最後に一言

Hibernate Validatior は意外と地雷が多いぞ! 気をつけろ。

  1. 正直 xxxUtils ってあまり勧めたくない。 しかし Java には拡張メソッドないししょうがない。オーバーライドすることもできないのはほんとにつらい……

  2. https://qiita.com/wingsys/items/1cb9e1175a9c542b2860

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?