§Using Custom Validations

The validation package allows you to create ad-hoc constraints using the verifying method. However, Play gives you the option of creating your own custom constraints, using the Constraint case class.

Here, we’ll implement a simple password strength constraint that uses regular expressions to check the password is not all letters or all numbers. A Constraint takes a function which returns a ValidationResult, and we use that function to return the results of the password check:

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) {
    } else {

Note: This is an intentionally trivial example. Please consider using the OWASP guide for proper password security.

We can then use this constraint together with Constraints.min to add additional checks on the password.

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

Next: Custom Field Constructors

Dokümantasyonun bu çevirisi Play ekibi tarafından yapılmamaktadır. Eğer bir hata bulduysanız, bu sayfanın kaynak kodu burada bulunmaktadır. Dokümantasyon yönergelerini okuduktan sonra lütfen katkı yapmaktan çekinmeyin.