Documentation

You are viewing the documentation for the 2.6.x development release. The latest stable release series is 2.4.x.

§カスタムバリデーションの使用

バリデーションパッケージ では、verifying メソッドを使ってアドホック制約を作成することができます。しかし Play では、Constraint ケースクラスを使用して独自のカスタム制約を作成する、という選択肢が提供されています。

ここでは、正規表現を使用して、パスワードが「すべて文字」ではない、または「すべて数字」ではないことを確認する簡単なパスワード強度の制約を実装してみます。ConstraintValidationResult を返す関数を取り、その関数を使ってパスワードチェックの結果を返します。

val allNumbers = """\d*""".r
val allLetters = """[A-Za-z]*""".r

val passwordCheckConstraint: Constraint[String] = Constraint("constraints.passwordcheck")({
  plainText =>
    val errors = plainText match {
      case allNumbers() => Seq(ValidationError("Password is all numbers"))
      case allLetters() => Seq(ValidationError("Password is all letters"))
      case _ => Nil
    }
    if (errors.isEmpty) {
      Valid
    } else {
      Invalid(errors)
    }
})

メモ: ここではあえて簡単な例にしています。適切なパスワードのセキュリティについては、OWASP ガイド の使用を検討してください。

この制約を Constraints.min と共に使用して、パスワードのチェックを追加できます。

val passwordCheck: Mapping[String] = nonEmptyText(minLength = 10)
  .verifying(passwordCheckConstraint)

Next: カスタムフィールドコンストラクタ


このドキュメントの翻訳は Play チームによってメンテナンスされているものではありません。 間違いを見つけた場合、このページのソースコードを ここ で確認することができます。 ドキュメントガイドライン を読んで、お気軽にプルリクエストを送ってください。