Search code examples
scalaplayframeworkplayframework-2.5playframework-json

how to check whether the given field is alphanumeric or not in PlayFramework


i have to check either the password field is alphanumeric or not and if not it will throw custom Validation error i am using play-framework but getting compile time error

value checkAlphanumeric is not a member of 
     play.api.libs.json.Reads[String]
    - value checkAlphanumeric is not a member of 
     play.api.libs.json.Reads[String]

i am unable to achive my desired outcome i am doing it wrong that's why i need here is the code

case class userUserSignUpValidation(firstName: String,
                                      lastName: String,
                                      email: String,
                                      password: String) extends Serializable

object UserSignUpValidation {
  val allNumbers = """\d*""".r
  val allLetters = """[A-Za-z]*""".r
  var validationErrorMsg=""
  implicit val readDirectUser: Reads[DirectUserSignUpValidation] = (
    (JsPath \ "firstName").read(minLength[String](1)) and
    (JsPath \ "lastName").read(minLength[String](1)) and
    (JsPath \ "email").read(email) and
    (JsPath \ "password").read(minLength[String](8)checkAlphanumeric))(UserSignUpValidation.apply _)
    def checkAlphanumeric(password:String)={
        val allNumbers = """\d*""".r
        val allLetters = """[A-Za-z]*""".r

        val errors = password match {
          case allNumbers() => Seq(ValidationError("Password is all numbers"))
          case allLetters() => Seq(ValidationError("Password is all letters"))
          case _ => Nil
        }
     }

i am getting the error on this line

(JsPath \ "password").read(minLength[String](8)checkAlphanumeric))(UserSignUpValidation.apply _)

what is the right way to implement an above scenario


Solution

  • Your problem is that you cannot use your checkAlphanumeric method that way. What you probably want is a filter on the Reads, so I would suggest doing something as follow (I changed the implementation for the check, using pre-existing methods):

    implicit val readDirectUser: Reads[DirectUserSignUpValidation] = (
      (JsPath \ "firstName").read(minLength[String](1)) and
        (JsPath \ "lastName").read(minLength[String](1)) and
        (JsPath \ "email").read(email) and
        (JsPath \ "password").read(minLength[String](8).
          filterNot(ValidationError("Password is all numbers"))(_.forall(_.isDigit)).
          filterNot(ValidationError("Password is all letters"))(_.forall(_.isLetter))
        )) (UserSignUpValidation.apply _)