Documentation

You are viewing the documentation for the 2.6.11 release in the 2.6.x series of releases. The latest stable release series is 3.0.x.

§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) {
      Valid
    } else {
      Invalid(errors)
    }
})

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)
  .verifying(passwordCheckConstraint)

Next: Custom Field Constructors