• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala ValidationError类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中play.api.data.validation.ValidationError的典型用法代码示例。如果您正苦于以下问题:Scala ValidationError类的具体用法?Scala ValidationError怎么用?Scala ValidationError使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ValidationError类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: PullRequest

//设置package包名称以及导入依赖的类
package models

import play.api.data.validation.ValidationError
import play.api.libs.functional.syntax._
import play.api.libs.json._

import scalaz._
import scalaz.Scalaz._

case class PullRequest(number: Double, owner: String, projectName: String)

object PullRequest {
  def buildFrom(json: JsValue): Seq[(JsPath, Seq[ValidationError])] \/ PullRequest = {
    val prReads: Reads[PullRequest] = (
      (__ \ "issue" \ "number").read[Double] and
        (__ \ "repository" \ "owner" \ "login").read[String] and
        (__ \ "repository" \ "name").read[String]
      ) (PullRequest.apply _)
    json.validate(prReads).asEither.disjunction
  }
} 
开发者ID:MiroslavCsonka,项目名称:u-cant-merge-this,代码行数:22,代码来源:PullRequest.scala


示例2: RichJsError

//设置package包名称以及导入依赖的类
package play.api.libs.json

import play.api.data.validation.ValidationError
import play.api.i18n.Messages

object RichJsError {

  def toI18NJson(e: JsError)(messages: Messages): JsObject = toI18NJson(e.errors)(messages)

  private def toI18NJson(errors: Seq[(JsPath, Seq[ValidationError])])(messages: Messages): JsObject = {
    val argsWrite = Writes.traversableWrites[Any](Writes.anyWrites)
    errors.foldLeft(Json.obj()) { (obj, error) =>
      obj ++ Json.obj(error._1.toJsonString -> error._2.foldLeft(Json.arr()) { (arr, err) =>
        arr :+ JsString( play.api.i18n.Messages(err.messages, err.args)(messages) )
      })
    }
  }

} 
开发者ID:LabCo,项目名称:rpi-zway-play,代码行数:20,代码来源:RichJsError.scala


示例3: JsonFormats

//设置package包名称以及导入依赖的类
package com.chriswk.gameranker.utils

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {

  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }
  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))
  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }
  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }
  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
      Try(Duration.parse(str)).toOption
    })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }


} 
开发者ID:chriswk,项目名称:gameranker,代码行数:60,代码来源:JsonFormats.scala


示例4: DockerEnvironment

//设置package包名称以及导入依赖的类
package codacy.dockerApi

import java.nio.file.{Files, Paths}

import codacy.dockerApi.api.CodacyConfiguration
import play.api.data.validation.ValidationError
import play.api.libs.json.{JsError, JsPath, Json}

import scala.util.{Failure, Success, Try}

object DockerEnvironment {

  def config: Try[CodacyConfiguration] = Try(Files.readAllBytes(configFilePath)).transform(
    raw => Try(Json.parse(raw)).flatMap(
      _.validate[CodacyConfiguration].fold(
        asFailure,
        conf => Success(conf)
      )),
    error => Failure(error)
  )

  private[this] def asFailure(error: Seq[(JsPath, Seq[ValidationError])]) =
    Failure(new Throwable(Json.stringify(JsError.toFlatJson(error.toList))))

  private[this] lazy val configFilePath = sourcePath.resolve(".codacyrc")

  lazy val sourcePath = Paths.get("/src")
} 
开发者ID:codacy,项目名称:codacy-duplication-scala-seed,代码行数:29,代码来源:DockerEnvironment.scala


示例5: CartEntry

//设置package包名称以及导入依赖的类
package persistence

import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

case class CartEntry(productName: String, count: Int)
case class Cart(user: UUID, cartItems: Seq[CartEntry])
case class Product(name: String, description: String, imageResource: String, price: Double)

object CartEntry {
  implicit val format = Json.format[CartEntry]
}

object Cart {
  def parseUUID(s: String): Option[java.util.UUID] = Try(java.util.UUID.fromString(s)).toOption

  implicit val uuidFormat = new Format[UUID] {
    def reads(json: JsValue): JsResult[UUID] = json match {
      case JsString(s) =>
        parseUUID(s).map(JsSuccess(_)).getOrElse(JsError(Seq(JsPath() -> Seq(ValidationError("Expected UUID string")))))
      case _ =>
        JsError(Seq(JsPath() -> Seq(ValidationError("Expected UUID string"))))
    }
    def writes(uuid: java.util.UUID): JsValue = JsString(uuid.toString)
  }

  implicit val format = Json.format[Cart]
} 
开发者ID:emotecontrol,项目名称:cart_play,代码行数:33,代码来源:Models.scala


示例6: JsonFormats

//设置package包名称以及导入依赖的类
package com.eevolution.utils

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {

  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }

  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))

  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }

  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }

  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
      Try(Duration.parse(str)).toOption
    })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }
} 
开发者ID:adempiere,项目名称:ADReactiveSystem,代码行数:62,代码来源:JsonFormats.scala


示例7: Errors

//设置package包名称以及导入依赖的类
package arcade

import play.api.data.validation.ValidationError
import play.api.libs.json._

object Errors {
  case object DuplicateAdmiral         extends Error
  case object AdmiralNotFound          extends Error

  case object DuplicateAnchor          extends Error
  case object AnchorNotFound           extends Error

  case object DuplicateSpotting        extends Error
  case object SpottingNotFound         extends Error
  case object TooShortSpottingInterval extends Error
  case object AnchorAlreadySpotted     extends Error
  case object AnchorAlreadySunk        extends Error

  case object Maintenance              extends Error

  case class JsonParseError(jsError: JsError) extends Error {
    override def toJson: JsObject = super.toJson.deepMerge(jsError.toJson)
  }
  object JsonParseError {
    def apply(errors: Seq[(JsPath, Seq[ValidationError])]): JsonParseError = JsonParseError(JsError(errors))
  }

  sealed trait Error {
    this: Product =>

    def code: String = productPrefix
    def toJson: JsObject = Json.obj("code" -> code)
  }

  private implicit val validationErrorWrites: Writes[ValidationError] = new Writes[ValidationError] {
    override def writes(o: ValidationError): JsValue = Json.obj(
      "messages" -> o.messages,
      "args"     -> o.args.map(_.toString)
    )
  }

  private implicit class JsErrorOps(val self: JsError) extends AnyVal {
    def toJson: JsObject = {
      Json.obj(
        "errors" -> self.errors.map { case (jsPath, error) =>
          Json.obj(
            "path" -> jsPath.toString,
            "error" -> error.map(Json.toJson(_))
          )
        }
      )
    }
  }

} 
开发者ID:harry0000,项目名称:KancolleAnchor,代码行数:56,代码来源:Errors.scala


示例8: jsonException

//设置package包名称以及导入依赖的类
package org.birdfeed.chirp.errors

import play.api.data.validation.ValidationError
import play.api.libs.json.{JsError, JsPath, JsValue, Json}

trait JsonError {
  def jsonException(message: String, exception: Exception = new Exception): JsValue = {
    Json.obj(
      "error" -> message,
      "details" -> Json.obj(
        "exception_class" -> exception.getClass.toString,
        "message" -> exception.toString
      )
    )
  }

  def jsonError(message: String): JsValue = Json.obj(
    "error" -> message
  )

  def jsonValidationError(message: String, errors: Seq[(JsPath, Seq[ValidationError])]): JsValue = {
    Json.obj("error" -> message, "details" -> JsError.toJson(errors))
  }
} 
开发者ID:AwesomeIT,项目名称:chirp,代码行数:25,代码来源:JsonError.scala


示例9: JsonFormats

//设置package包名称以及导入依赖的类
package com.example.auction.utils

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {

  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }
  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))
  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }
  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }
  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
      .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
        Try(Duration.parse(str)).toOption
      })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }


} 
开发者ID:lagom,项目名称:online-auction-scala,代码行数:60,代码来源:JsonFormats.scala


示例10: JsonFormats

//设置package包名称以及导入依赖的类
package org.wex.cmsfs.monitor.api

import java.time.Duration
import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {
  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = Reads {
    case JsString(s) =>
      try {
        JsSuccess(enum.withName(s).asInstanceOf[E#Value])
      } catch {
        case _: NoSuchElementException =>
          JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not contain '$s'")
      }
    case _ => JsError("String value expected")
  }
  def enumWrites[E <: Enumeration]: Writes[E#Value] = Writes(v => JsString(v.toString))
  def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }

  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }
  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }
  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }

  implicit val durationReads: Reads[Duration] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid duration"))(Function.unlift { str =>
      Try(Duration.parse(str)).toOption
    })
  implicit val durationWrites: Writes[Duration] = Writes { duration =>
    JsString(duration.toString)
  }
} 
开发者ID:shinhwazx160,项目名称:test,代码行数:57,代码来源:JsonFormats.scala


示例11: Vote

//设置package包名称以及导入依赖的类
package models

import play.api.data.validation.ValidationError
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._

import slick.driver.MySQLDriver.api.{Tag => SlickTag}
import slick.driver.MySQLDriver.api._

case class Vote(answer_id: Option[Long], user_id: Option[Long], value: Int)

object Vote {
  val userValidate = Reads.IntReads.
    filter(ValidationError("Value must be -1 or 1"))(validValue(_))

  implicit val voteReads: Reads[Vote] = (
    (JsPath \ "answer_id").readNullable[Long] and
    (JsPath \ "user_id").readNullable[Long] and
    (JsPath \ "value").read[Int](userValidate)
  )(Vote.apply _)

  implicit val voteWrites = Json.writes[Vote]

  def validValue(value: Int) = value == -1 || value == 1
}

class VoteTable(tag: SlickTag) extends Table[Vote](tag, "votes") {
  def answer_id = column[Option[Long]]("answer_id")
  def user_id = column[Option[Long]]("user_id")
  def value = column[Int]("vote_value")

  def pk = primaryKey("vote_pk", (answer_id, user_id))

  def * = (answer_id, user_id, value) <> ((Vote.apply _).tupled, Vote.unapply)
} 
开发者ID:greven77,项目名称:PlaySlickTest,代码行数:37,代码来源:Vote.scala


示例12: SortingPaginationWrapper

//设置package包名称以及导入依赖的类
package utils

import play.api.data.validation.ValidationError
import play.api.libs.json._
import play.api.libs.functional.syntax._

case class SortingPaginationWrapper(sort_by: String,
  page: Int = 1,
  resultsPerPage: Int = 25, direction: String = "desc")

object SortingPaginationWrapper {

  val sortingParameters = List("date", "votes", "title")
  val directionParameters = List("asc", "desc")

  val sortValidate = Reads.StringReads.
    filter(ValidationError("invalid parameter"))(sortByValidator(_))

  val sortValidateAnswers = Reads.StringReads.
    filter(ValidationError("invalid parameter"))(sortByValidator)

  val directionValidate = Reads.StringReads.
    filter(ValidationError("invalid parameter"))(directionValidator(_))

  implicit val sortingPaginationReads: Reads[SortingPaginationWrapper] = (
    ((JsPath \ "sort_by").read[String](sortValidate) orElse Reads.pure("date")) and
    ((JsPath \ "page").read[Int] orElse Reads.pure(1)) and
    ((JsPath \ "resultsPerPage").read[Int] orElse Reads.pure(25)) and
    ((JsPath \ "direction").read[String](directionValidate) orElse Reads.pure("desc"))
  )(SortingPaginationWrapper.apply _)

  val sortingPaginationAnswerReads: Reads[SortingPaginationWrapper] = (
    ((JsPath \ "sort_by").read[String](sortValidateAnswers) orElse Reads.pure("created_at")) and
    ((JsPath \ "page").read[Int] orElse Reads.pure(1)) and
    ((JsPath \ "resultsPerPage").read[Int] orElse Reads.pure(25)) and
    ((JsPath \ "direction").read[String](directionValidate) orElse Reads.pure("desc"))
  )(SortingPaginationWrapper.apply _)


  def sortByValidator(criteria: String) =
    List("date", "votecount", "title", "answercount", "favouritecount")
      .contains(criteria.toLowerCase)

  def sortByValidatorAnswers(criteria: String) =
    List("created_at", "updated_at", "voteCount").contains(criteria.toLowerCase)

  def directionValidator(param: String) =
    List("asc", "desc").contains(param.toLowerCase)

  def getPage(pageNum: Int, resultsPerPage: Int) =
    resultsPerPage * (pageNum - 1)
} 
开发者ID:greven77,项目名称:PlaySlickTest,代码行数:53,代码来源:SortingPaginationWrapper.scala


示例13: Validation

//设置package包名称以及导入依赖的类
package utils

import play.api.Play.current
import play.api.data.validation.ValidationError
import play.api.i18n.Messages
import play.api.i18n.Messages.Implicits._
import play.api.libs.json.Json._
import play.api.libs.json.{JsObject, JsPath, Json}
import play.api.mvc._

import scala.concurrent.Future


object Validation extends Controller {

  def validationError(code: Int)(errors: Seq[(JsPath, Seq[ValidationError])]): Future[Result] = {
    def messageFormat: JsObject = {
      errors.foldLeft(Json.obj()) { (obj, error) =>
        obj ++ Json.obj(error._1.toString().replaceFirst(Constants.Global.SLASH, Constants.Global.EMPTY_STRING) -> error._2.foldLeft(Json.arr()) { (arr, err) =>
          arr :+ Json.obj(Constants.Global.MESSAGE -> Messages(err.message, if (err.args.nonEmpty) err.args.head).toString)
        })
      }
    }
    Future.successful(BadRequest(obj(Constants.Global.STATUS -> code, Constants.Global.ERROR_MESSAGE -> messageFormat)))
  }
} 
开发者ID:satriapribadi,项目名称:satriapribadi.com,代码行数:27,代码来源:Validation.scala


示例14: ValidationUtils

//设置package包名称以及导入依赖的类
package utils

import play.api.data.validation.{Constraint, Invalid, Valid, ValidationError}

object ValidationUtils {

  def inRange[T](minValue: T, maxValue: T)(implicit ordering: scala.math.Ordering[T]): Constraint[T] =
    Constraint[T] { (t: T) =>
      assert(ordering.compare(minValue, maxValue) < 0, "min bound must be less than max bound")
      (ordering.compare(t, minValue).signum, ordering.compare(t, maxValue).signum) match {
        case (1, -1) | (0, _) | (_, 0) => Valid
        case (_, 1) => Invalid(ValidationError("error.range.above", maxValue))
        case (-1, _) => Invalid(ValidationError("error.range.below", minValue))
      }
    }

  def optionallyMatchingPattern(regex: String): Constraint[String] =
    Constraint[String] { s: String =>
      Option(s) match {
        case None | Some("") => Valid
        case _ if s.matches(regex) => Valid
        case _ => Invalid(ValidationError("error.string.pattern", s))
      }
    }

} 
开发者ID:PeterPerhac,项目名称:vehicle-lookup,代码行数:27,代码来源:ValidationUtils.scala


示例15: JsonFormats

//设置package包名称以及导入依赖的类
package com.example.lagompractice.utils

import java.util.UUID

import play.api.data.validation.ValidationError
import play.api.libs.json._

import scala.util.Try

object JsonFormats {


  def singletonReads[O](singleton: O): Reads[O] = {
    (__ \ "value").read[String].collect(
      ValidationError(s"Expected a JSON object with a single field with key 'value' and value '${singleton.getClass.getSimpleName}'")
    ) {
      case s if s == singleton.getClass.getSimpleName => singleton
    }
  }
  def singletonWrites[O]: Writes[O] = Writes { singleton =>
    Json.obj("value" -> singleton.getClass.getSimpleName)
  }
  def singletonFormat[O](singleton: O): Format[O] = {
    Format(singletonReads(singleton), singletonWrites)
  }

  implicit val uuidReads: Reads[UUID] = implicitly[Reads[String]]
    .collect(ValidationError("Invalid UUID"))(Function.unlift { str =>
      Try(UUID.fromString(str)).toOption
    })
  implicit val uuidWrites: Writes[UUID] = Writes { uuid =>
    JsString(uuid.toString)
  }
} 
开发者ID:Saneyan,项目名称:lagom-practice,代码行数:35,代码来源:JsonFormats.scala


示例16: Status

//设置package包名称以及导入依赖的类
package kipsigman.domain.entity

import play.api.data.validation.ValidationError
import play.api.libs.json._

abstract class Status(val name: String) {
  override def toString: String = name
}

object Status {
  // Content
  case object Deleted extends Status("deleted")
  case object Draft extends Status("draft")
  case object Public extends Status("public")
  case object Unlisted extends Status("unlisted")
  
  // Reviewed entity
  case object Approved extends Status("approved")
  case object Pending extends Status("pending")
  case object Rejected extends Status("rejected")
  
  val all: Set[Status] = Set(Deleted, Draft, Public, Unlisted, Approved, Pending, Rejected)
  val activeValues: Set[Status] = Set(Draft, Public, Unlisted, Approved, Pending)
  val publishValues: Set[Status] = Set(Public, Unlisted)
  
  def apply(name: String): Status = {
    all.find(s => s.name == name) match {
      case Some(status) => status
      case None => throw new IllegalArgumentException(s"Invalid Status: $name")
    }
  }
  
  implicit val reads: Reads[Status] = new Reads[Status] {
    def reads(json: JsValue) = json match {
      case JsString(s) => JsSuccess(Status(s))
      case _ => JsError(Seq(JsPath() -> Seq(ValidationError("error.expected.jsstring"))))
    }
  }
  
  implicit val writes: Writes[Status] = new Writes[Status] {
    def writes(status: Status) = JsString(status.name)
  }
} 
开发者ID:kipsigman,项目名称:scala-domain-model,代码行数:44,代码来源:Status.scala


示例17: RQLTokens

//设置package包名称以及导入依赖的类
package io.really.rql

import play.api.data.validation.ValidationError
import play.api.libs.json._

object RQLTokens {

  case class PaginationToken(id: Long, direction: Int) {
    require(direction == 0 | direction == 1, s"paginationToken '$id:$direction' direction must be 0 or 1.")
  }

  object PaginationToken {
    def parse(token: String): JsResult[PaginationToken] = {
      token.split(":").toList match {
        case id :: dir :: Nil =>
          try {
            JsSuccess(PaginationToken(id.toLong, dir.toInt))
          } catch {
            case e: NumberFormatException =>
              JsError(Seq(JsPath() -> Seq(ValidationError("error.invalid.token.format"))))
          }
        case _ =>
          JsError(Seq(JsPath() -> Seq(ValidationError("error.invalid.token.format"))))
      }
    }

    implicit val writes = new Writes[PaginationToken] {
      def writes(token: PaginationToken): JsValue = JsString(s"${token.id}:${token.direction}")
    }

    implicit val reads = new Reads[PaginationToken] {
      def reads(jsToken: JsValue): JsResult[PaginationToken] =
        jsToken match {
          case JsString(token) => parse(token)
          case _ => JsError(Seq(JsPath() -> Seq(ValidationError("error.expected.String"))))
        }
    }
  }

} 
开发者ID:radiodb,项目名称:radiodb,代码行数:41,代码来源:RQLTokens.scala


示例18: RQLTokensSpec

//设置package包名称以及导入依赖的类
package io.really.rql

import io.really.rql.RQLTokens.PaginationToken
import org.scalatest.{ Matchers, FlatSpec }
import play.api.data.validation.ValidationError
import play.api.libs.json._

class RQLTokensSpec extends FlatSpec with Matchers {

  "PaginationToken" should "fail when trying to generate token with direction isn't equal 0 or 1" in {
    intercept[IllegalArgumentException] {
      PaginationToken(12345678908765432l, 4)
    }
  }

  it should "be readable from JsValue" in {
    JsString("111111113333:0").validate(PaginationToken.reads).get should equal(PaginationToken(111111113333l, 0))
  }

  it should "Write QueryToken to JsValue" in {
    val token = PaginationToken(2133121331, 0)
    Json.toJson(token) should equal(JsString("2133121331:0"))
  }

  "PaginationToken Parsing" should "pass if the string is a valid one" in {
    val tokenResult = PaginationToken.parse("1231231234532:1")
    tokenResult should equal(JsSuccess(PaginationToken(1231231234532l, 1)))
  }

  it should "fail if the string hasn't direction as integer" in {
    val tokenResult = PaginationToken.parse("1231231234532:X")
    tokenResult.isInstanceOf[JsError] shouldBe true
    tokenResult.asInstanceOf[JsError].errors.contains(Seq(JsPath() -> Seq(ValidationError("error.invalid.token.format"))))
  }

} 
开发者ID:radiodb,项目名称:radiodb,代码行数:37,代码来源:RQLTokensSpec.scala


示例19: validate

//设置package包名称以及导入依赖的类
package services

import controllers.{LoanRequest, OfferRequest}
import play.api.data.validation.{Invalid, Valid, ValidationError, ValidationResult}

trait Validation {

  def validate(loanRequest: LoanRequest): ValidationResult = {
    val amountErrors = if (loanRequest.amount <= 0) Seq(ValidationError("Invalid amount")) else Seq()
    val daysErrors = if (loanRequest.durationInDays <= 0) Seq(ValidationError("Invalid duration")) else Seq()
    val errors = amountErrors ++ daysErrors
    if (errors.isEmpty)
      Valid
    else
      Invalid(errors)
  }

  def validate(offerRequest: OfferRequest): ValidationResult = {
    if (offerRequest.amount <= 0)
      Invalid(Seq(ValidationError("Invalid amount")))
    else Valid
  }

} 
开发者ID:sindoudou,项目名称:crowd-funding-loans,代码行数:25,代码来源:Validation.scala


示例20: ValidationSpec

//设置package包名称以及导入依赖的类
package com.sg.loan

import controllers.{LoanRequest, OfferRequest}
import org.scalatest.{MustMatchers, WordSpec}
import play.api.data.validation.{Invalid, Valid, ValidationError}
import services.Validation

class ValidationSpec extends WordSpec with MustMatchers with Validation {

  "Validation" should {
    "return a valid response when creating a valid loan" in {
      validate(LoanRequest(10, 3)) mustBe Valid
    }
  }

  "Validation" should {
    "return an invalid response when creating a loan with negative amount" in {
      validate(LoanRequest(-10, 3)) mustBe Invalid(Seq(ValidationError("Invalid amount")))
    }
  }

  "Validation" should {
    "return an invalid response when creating a loan with negative duration" in {
      validate(LoanRequest(10, -3)) mustBe Invalid(Seq(ValidationError("Invalid duration")))
    }
  }

  "Validation" should {
    "return a valid response when creating a valid offer" in {
      validate(OfferRequest(10, 3)) mustBe Valid
    }
  }

  "Validation" should {
    "return an invalid response when creating an offer with negative amount" in {
      validate(OfferRequest(-10, 3)) mustBe Invalid(Seq(ValidationError("Invalid amount")))
    }
  }
} 
开发者ID:sindoudou,项目名称:crowd-funding-loans,代码行数:40,代码来源:ValidationSpec.scala



注:本文中的play.api.data.validation.ValidationError类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala HttpEntity类代码示例发布时间:2022-05-23
下一篇:
Scala HashSet类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap