readNullable在使用play2的scala中不起作用

时间:2015-05-06 12:51:43

标签: json scala playframework-2.0

我正在验证来自UI的json 我在case类中有一个可选字段,用于验证和解析json 这是

case class SignUpValidation(firstNname : String, 
                                          var lastName: String, 
                                          var email: String,
                                          var secondryEmail : Option[String] )
object SignUpValidation {

  implicit val artworkReads: Reads[SignUpValidation] = (
(JsPath \ "firstname").read(minLength[String](1)) and
(JsPath \ "lastname").read(minLength[String](1)) and
(JsPath \ "email").read(email) and
(JsPath \ "secondryemail").readNullable(email)
)(SignUpValidation.apply _)

}

我正在验证这样的传入请求

jsonRequest.validate[SignUpValidation].fold(
      valid = {
 // validation successful
 }, 
 invalid = {
 // validation failed
  } )

当我没有在secondryEmail中输入任何内容并提交数据时,验证应该成功但是无效的块运行 请指导我什么是我的错误

2 个答案:

答案 0 :(得分:0)

我认为你必须将表单翻译成JSON。从上面看起来它可能是一个空数组?我能够使用不存在的辅助电子邮件或空的辅助电子邮件进行验证,如下所示:

import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._

case class SignUpValidation(firstNname : String,
                        var lastName: String,
                        var email: String,
                        var secondryEmail : Option[String] )

object SignUpValidation {
 implicit val artworkReads: Reads[SignUpValidation] = (
  (JsPath \ "firstname").read(minLength[String](1)) and
  (JsPath \ "lastname").read(minLength[String](1)) and
  (JsPath \ "email").read(email) and
  (JsPath \ "secondryemail").readNullable(email)
)(SignUpValidation.apply _)
}


val js =
"""{
   |"firstname":"bob",
   |"lastname":"frank",
   |"email":"bob@gmail.com",
   |"secondaryemail":""
   |}
 """.stripMargin


val result = Json.parse(js).validate[SignUpValidation]

println(result)


val js2 =
 """{
    |"firstname":"bob",
    |"lastname":"frank",
    |"email":"bob@gmail.com"
    |}
  """.stripMargin


val result2 = Json.parse(js2).validate[SignUpValidation]

println(result2)

控制台输出

js: String =
 "{
   "firstname":"bob",
   "lastname":"frank",
   "email":"bob@gmail.com",
   "secondaryemail":""
 }"
result: play.api.libs.json.JsResult[SignUpValidation] =      JsSuccess(SignUpValidation(bob,frank,bob@gmail.com,None),)
js2: String =
 "{
  "firstname":"bob",
  "lastname":"frank",
   "email":"bob@gmail.com"
 }"

result2: play.api.libs.json.JsResult[SignUpValidation] =     JsSuccess(SignUpValidation(bob,frank,bob@gmail.com,None),)

答案 1 :(得分:0)

首先要小心你的提示,它可能会导致你的代码出现拼写错误。我知道这是有效的:

首先使用Companion对象的案例类

package models

import play.api.libs.json.{JsPath, Reads}
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._

/**
 * Created by anquegi on 06/05/15.
 */
case class SignUpValidation(firstNname : String,
                            var lastName: String,
                            var email: String,
                            var secondryEmail : Option[String] ){
}

object SignUpValidation {

  implicit val SignUpValidationReads: Reads[SignUpValidation] = (
    (JsPath \ "firstname").read(minLength[String](1)) and
      (JsPath \ "lastname").read(minLength[String](1)) and
      (JsPath \ "email").read(email) and
      (JsPath \ "secondryemail").readNullable(email)
    )(SignUpValidation.apply _)

}

然后是你控制器中的POST方法

package controllers


import models.SignUpValidation
import play.api.libs.json.{JsError, Json}
import play.api.mvc._

object Application extends Controller {

  def index = Action {

    Ok("Play Framework Scala Stack OverFlow")

  }

  def testSignUpValidation = Action(BodyParsers.parse.json) { request =>

    val signup = request.body.validate[SignUpValidation]

    signup.fold(
      errors => {
        BadRequest(Json.obj("status" ->"KO", "message" -> JsError.toFlatJson(errors)))
      },

      signupObj => {

        Ok(Json.obj("status" ->"OK", "message" -> ("signup "+signupObj.toString) ))
      }
    )
  }

使用路由中的URL:

POST   /testsignupvalidation controllers.Application.testSignUpValidation

我使用curl来自用户Barry的JSON来测试它:

[anquegi@localhost ~]$ curl --include --request POST --header "Content-type: application/json"  --data '{"firstname":"bob","lastname":"frank","email":"bob@gmail.com"}' http://localhost:9000/testsignupvalidation
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 81

{"status":"OK","message":"signup SignUpValidation(bob,frank,bob@gmail.com,None)"}


[anquegi@localhost ~]$ curl --include --request POST --header "Content-type: application/json"  --data '{    "firstname":"bob",    "lastname":"frank",    "email":"bob@gmail.com",    "secondryemail":"bob2@gmail.com"  }' http://localhost:9000/testsignupvalidation
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 97

{"status":"OK","message":"signup SignUpValidation(bob,frank,bob@gmail.com,Some(bob2@gmail.com))"}

小心使用secondryemail和secondaryemail 当它是一个空字符串时你不应该提交secondryemail,在其他情况下它会被邮件验证器失败,如下所示:

[anquegi@localhost ~]$ curl --include --request POST --header "Content-type: application/json"  --data '{    "firstname":"bob",    "lastname":"frank",    "email":"bob@gmail.com",    "secondryemail":""  }' http://localhost:9000/testsignupvalidation
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 81

{"status":"KO","message":{"obj.secondryemail":[{"msg":"error.email","args":[]}]}