35
33

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.

Playframeworkのフォームで良く使うバリデーション

Last updated at Posted at 2015-02-10

Playframeworkでフォームを扱うときに、個人的に良く使うバリデーションのまとめ。
ただ制約など書き方が複数あるものは、良く使う1パターンのみ書きます。

複雑なフォームを定義しない限り、ここにあるもので大体カバーできると思う。

種類

文字とか数値とか

case class MyForm(name:String, age:Int)

val myForm = Form(
	mapping(
		// 文字列
		"name" -> text,	
		// 数値
		"age" -> number	
	)(MyForm.apply)(MyForm.unapply)
)

制約

長さとかパターンとか

case class MyForm(naem:String, handleName:String, age:Int, email:String)

val emailPattern = Constraints.pattern("[\\w\\d_-]+@[\\w\\d_-]+\\.[\\w\\d._-]+".r)

val myForm = Form(
	mapping(
		// 必須
		"name" -> nonEmptyText,
		// 文字数 (3文字以上、7文字以下)
		"handleName" -> text(minLength = 3, maxLength = 7),
		// 最大最小 (最小:0、最大:100)
		"age" -> number(min = 0, max = 100),
		// 正規表現 (メールアドレス)
		"email" -> text.verifying(emailPattern)
	)(MyForm.apply)(MyForm.unapply)
)

入力値の一致確認

パスワードとパスワード(確認)とか

case class MyForm(password:String)

val myForm = Form(
	mapping(
		// password1とpassword2が一致すること
		"password" ->
        	tuple(
          		"password1" -> nonEmptyText,
          		"password2" -> nonEmptyText
        	).verifying(passwords => passwords._1 == passwords._2)
	)(MyForm.apply)(MyForm.unapply)
)

複数のバリデーション

制約を複数つける

case class MyForm(password:String)

val halfWidthAlphaNum = Constraints.pattern("[a-zA-Z0-9]+".r)

val myForm = Form(
	mapping(
		// password1とpassowrd2が一致、かつ、半角英数字
		"password" ->
        	tuple(
          		"password1" -> nonEmptyText,
          		"password2" -> nonEmptyText
        	).verifying(passwords => passwords._1 == passwords._2).verifying(halfWidthAlphaNum)
	)(MyForm.apply)(MyForm.unapply)
)

デフォルト値

入力あればその値、無かったらデフォルト値

case class MyForm(year:Int, month:Int)

val myForm = Form(
	mapping(
		// デフォルト値: 2015
		"year" -> default(number, 2015)
		// 最小:1、最大:12、デフォルト値: 1
		"month" -> default(number(min = 1, max = 12), 1)
	)(MyForm.apply)(MyForm.unapply)
)

省略

あったら使うし、無かったら使わない

case class MyForm(comment:Option[String])

val myForm = Form(
	mapping(
		// 省略可、文字数140文字以下
		"comment" -> Option(text(maxLength = 140))
	)(MyForm.apply)(MyForm.unapply)
)
35
33
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
35
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?