本文整理汇总了Scala中play.api.data.validation.Invalid类的典型用法代码示例。如果您正苦于以下问题:Scala Invalid类的具体用法?Scala Invalid怎么用?Scala Invalid使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Invalid类的16个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: TimeCostInput
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.shouldioptimize.model.{Ec2Pricing, PreTaxHourlyTimeCostModel}
import play.api.cache.Cached
import play.api.data.Forms._
import play.api.data._
import play.api.data.validation.{Constraint, Invalid, Valid, ValidationResult}
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc._
case class TimeCostInput(programmerHourCost: BigDecimal, instanceType: String)
class Application @Inject()(val messagesApi: MessagesApi, cached: Cached) extends Controller with I18nSupport {
val validInstanceType = Constraint[String] ({
case it if Ec2Pricing.all.contains(it) => Valid
case _ => Invalid("invalid instance type")
}: PartialFunction[String,ValidationResult])
val TimeCostInputForm = Form(
mapping(
"programmerHourCost" -> bigDecimal,
"instanceType" -> text.verifying(validInstanceType)
)(TimeCostInput.apply)(TimeCostInput.unapply))
private val DefaultProgrammerHourCost = BigDecimal("42.88")
private val DefaultInstanceType = "t2.large"
private val DefaultForm = TimeCostInputForm.fill(TimeCostInput(BigDecimal("42.88"), DefaultInstanceType))
def index = cached.status(_ => "/index", OK, 60) {
Action {
Ok(views.html.results(new PreTaxHourlyTimeCostModel(BigDecimal("42.88")).calculate.values, DefaultForm))
}
}
def results = Action { request =>
val form = TimeCostInputForm.bind(request.queryString.mapValues(_.head))
form.fold(
formWithErrors => BadRequest(views.html.results(new PreTaxHourlyTimeCostModel(DefaultProgrammerHourCost).calculate.values, formWithErrors)),
timeCostInput => Ok(views.html.results(new PreTaxHourlyTimeCostModel(timeCostInput.programmerHourCost).calculate.values, form))
)
}
def why = cached.status(_ => "/why", OK, 60) {
Action {
Ok(views.html.why())
}
}
}
开发者ID:ostewart,项目名称:shouldioptimize,代码行数:52,代码来源:Application.scala
示例2: NewLinkForm
//设置package包名称以及导入依赖的类
package models.forms
import models.LinkAddData
import play.api.data.Form
import play.api.data.Forms.{mapping, nonEmptyText, optional, text, longNumber}
import play.api.data.validation.{Constraint, Invalid, Valid}
object NewLinkForm {
private val urlRegex = "(^|[\\s.:;?\\-\\]<\\(])(https?://[-\\w;/?:@&=+$\\|\\_.!~*\\|'()\\[\\]%#,?]+[\\w/#](\\(\\))?)(?=$|[\\s',\\|\\(\\).:;?\\-\\[\\]>\\)])"
private val urlContraint = Constraint[String] { s: String =>
if (s.matches(urlRegex))
Valid
else
Invalid("is not a valid url")
}
val form = Form(
mapping(
"url" -> nonEmptyText.verifying(urlContraint),
"name" -> optional(text),
"description" -> optional(text),
"parentId" -> optional(longNumber)
)(LinkAddData.apply)(LinkAddData.unapply)
)
}
开发者ID:agoetschm,项目名称:linkmanager,代码行数:28,代码来源:NewLinkForm.scala
示例3: 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
示例4: 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
示例5: 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
示例6: ValidationUtils
//设置package包名称以及导入依赖的类
package utils
import java.time.LocalDate
import models.DateComponents
import org.apache.commons.lang3.StringUtils
import play.api.data.format.Formatter
import play.api.data.validation.{Constraint, Invalid, Valid, ValidationError}
import play.api.data.{FieldMapping, FormError, Forms}
import scala.util.{Failure, Success}
object ValidationUtils {
implicit val mandatoryBooleanFormatter = new Formatter[Boolean] {
def bind(key: String, data: Map[String, String]) = {
Right(data.getOrElse(key, "")).right.flatMap {
case "true" => Right(true)
case "false" => Right(false)
case _ => Left(Seq(FormError(key, s"$key.error.boolean", Nil)))
}
}
def unbind(key: String, value: Boolean) = Map(key -> value.toString)
}
val mandatoryBoolean: FieldMapping[Boolean] = Forms.of[Boolean]
val notBlank: (String) => Boolean = StringUtils.isNotBlank
def unconstrained[T] = Constraint[T] { (t: T) => Valid }
def inRange[T](minValue: T, maxValue: T, errorCode: String = "")(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(s"error$errorCode.range.above", maxValue))
case (-1, _) => Invalid(ValidationError(s"error$errorCode.range.below", minValue))
}
}
def validDate(constraint: Constraint[LocalDate] = unconstrained) = Constraint[DateComponents] {
(dcs: DateComponents) =>
DateComponents.toLocalDate(dcs) match {
case Failure(_) => Invalid(ValidationError("error.date.invalid", dcs))
case Success(localDate) => constraint(localDate)
}
}
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,项目名称:pocs,代码行数:61,代码来源:ValidationUtils.scala
示例7: Formatter
//设置package包名称以及导入依赖的类
package helpers
import org.joda.time.format.DateTimeFormat
import play.api.data.validation.ValidationError
import play.api.i18n.Messages
import play.api.data.validation.Constraint
import play.api.data.validation.Invalid
import play.api.i18n.MessagesProvider
object Formatter {
val yyyy_mm_dd = DateTimeFormat.forPattern("yyyy-MM-dd")
def validationErrorsToString(errors: Seq[ValidationError])(implicit mp: MessagesProvider): String =
errors.map {e => Messages(e.message, e.args: _*)}.mkString(Messages("PeriodSymbol"))
def validationErrorString[T](constraints: Seq[Constraint[T]], value: T)(implicit mp: MessagesProvider): String =
validationErrorsToString(
constraints.map(_.apply(value)).collect {
case Invalid(errors) => errors
}.flatten
)
}
开发者ID:ruimo,项目名称:store2,代码行数:21,代码来源:Formatter.scala
示例8: ArtistService
//设置package包名称以及导入依赖的类
package application.service
import java.sql.SQLIntegrityConstraintViolationException
import javax.inject.{ Inject, Singleton }
import controllers.model.{ ArtistRequest, ArtistResponse }
import domain.model.Artist
import infrastructure.repository.ArtistRepositoryJDBC
import play.api.data.validation.Invalid
import play.api.db.slick.{ DatabaseConfigProvider, HasDatabaseConfigProvider }
import slick.driver.JdbcProfile
import util.Id64
import scala.concurrent.{ ExecutionContext, Future }
import scalaz.{ Scalaz, \/ }
import Scalaz._
@Singleton
class ArtistService @Inject() (
artistRepositoryJDBC: ArtistRepositoryJDBC,
val dbConfigProvider: DatabaseConfigProvider
) extends HasDatabaseConfigProvider[JdbcProfile] {
def register(artistReq: ArtistRequest)(implicit ec: ExecutionContext): Future[Invalid \/ Artist] = {
val artist = Artist(Id64.nextAscId(), artistReq.name)
db.run(artistRepositoryJDBC.register(artist)).map(_ => artist.right).recover {
case e: SQLIntegrityConstraintViolationException => Invalid("duplicate").left
case e => throw e
}
}
def list()(implicit ec: ExecutionContext) = {
// TODO response?????controller ?
db.run(artistRepositoryJDBC.list).map(_.map(a => ArtistResponse(a.id.toString, a.name)).right[Invalid])
}
}
开发者ID:FScoward,项目名称:billets-en-concert,代码行数:37,代码来源:ArtistService.scala
示例9: PlaceService
//设置package包名称以及导入依赖的类
package application.service
import java.sql.SQLIntegrityConstraintViolationException
import javax.inject.{ Inject, Singleton }
import controllers.model.{ PlaceRequest, PlaceUpdateRequest }
import domain.model.Place
import infrastructure.repository.PlaceRepository
import play.api.data.validation.Invalid
import play.api.db.slick.{ DatabaseConfigProvider, HasDatabaseConfigProvider }
import slick.driver.JdbcProfile
import util.{ Id64, Logging }
import scala.concurrent.{ ExecutionContext, Future }
import scalaz.Scalaz._
import scalaz.{ EitherT, \/ }
@Singleton
class PlaceService @Inject() (
placeRepository: PlaceRepository,
val dbConfigProvider: DatabaseConfigProvider
) extends HasDatabaseConfigProvider[JdbcProfile] with Logging {
def register(placeRequest: PlaceRequest)(implicit ec: ExecutionContext): Future[Invalid \/ Place] = {
val place = Place(Id64.nextAscId(), placeRequest.name, placeRequest.address)
db.run(placeRepository.register(place)).map(_ => place.right).recover {
case e: SQLIntegrityConstraintViolationException => Invalid("duplicate").left
case e => throw e
}
}
def update(placeUpdateRequest: PlaceUpdateRequest)(implicit ec: ExecutionContext): EitherT[Future, Invalid, Place] = {
for {
place <- EitherT(db.run(placeRepository.findBy(placeUpdateRequest.id)).map(_ \/> Invalid("")))
updated = place.update(placeUpdateRequest.name, placeUpdateRequest.address)
_ <- EitherT(db.run(placeRepository.update(placeUpdateRequest.id, updated).map(_.right)))
} yield updated
}
}
开发者ID:FScoward,项目名称:billets-en-concert,代码行数:40,代码来源:PlaceService.scala
示例10: LiveController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import application.service.LiveService
import controllers.model.LiveRequest
import play.api.data.validation.Invalid
import play.api.mvc.{ Action, Controller }
import util.Logging
import scala.concurrent.{ ExecutionContext, Future }
import scalaz.EitherT
//import scalaz.syntax.std.all._
//import scalaz.syntax.std.ToEitherOps
import scalaz.Scalaz, Scalaz._
class LiveController @Inject() (
liveService: LiveService,
implicit val ec: ExecutionContext
) extends Controller with ControllerBase with Logging {
def create() = Action.async(parse.json) { request =>
val userName = request.session.get("userName")
val result = for {
valid <- EitherT(Future.successful(request.body.validate[LiveRequest].fold(invalid => Invalid(s"invalid request: ${invalid}").left, valid => valid.right)))
_ <- EitherT(liveService.create(valid))
} yield (valid)
result.toResult
}
def find(liveId: Long) = Action { request =>
Ok(s"${request.session}")
}
}
开发者ID:FScoward,项目名称:billets-en-concert,代码行数:37,代码来源:LiveController.scala
示例11: PlaceController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{ Inject, Singleton }
import application.service.PlaceService
import controllers.model.{ PlaceRequest, PlaceUpdateRequest }
import play.api.data.validation.Invalid
import play.api.libs.json.Json
import play.api.mvc.{ Action, Controller }
import scala.concurrent.{ ExecutionContext, Future }
import scalaz.EitherT
import scalaz.Scalaz._
@Singleton
class PlaceController @Inject() (
placeService: PlaceService,
implicit val ec: ExecutionContext
) extends Controller with ControllerBase {
def register() = Action.async(parse.json) { request =>
val read = request.body.validate[PlaceRequest].fold(
invalid => Invalid("invalid request").left,
valid => valid.right
)
val result = for {
valid <- EitherT(Future.successful(read))
place <- EitherT(placeService.register(valid))
} yield Json.obj("placeId" -> place.id.toString)
result.toResult
}
def update = Action.async(parse.json) { request =>
val read = request.body.validate[PlaceUpdateRequest].fold(
invalid => Invalid("invalid request").left,
valid => valid.right
)
val result = for {
valid <- EitherT(Future.successful(read))
place <- placeService.update(valid)
} yield place
result.toResult
}
}
开发者ID:FScoward,项目名称:billets-en-concert,代码行数:50,代码来源:PlaceController.scala
示例12: ArtistController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{ Inject, Singleton }
import application.service.ArtistService
import controllers.model.{ ArtistRequest, ArtistResponse }
import play.api.data.validation.Invalid
import play.api.mvc.{ Action, Controller }
import scalaz.{ EitherT, Scalaz }
import Scalaz._
import scala.concurrent.{ ExecutionContext, Future }
@Singleton
class ArtistController @Inject() (
artistService: ArtistService,
implicit val ec: ExecutionContext
) extends Controller with ControllerBase {
def register() = Action.async(parse.json) { implicit request =>
val read = request.body.validate[ArtistRequest].fold(
invalid => Invalid("invalid request").left,
valid => valid.right
)
val result =
for {
valid <- EitherT(Future.successful(read))
artist <- EitherT(artistService.register(valid))
} yield (ArtistResponse(artist.id.toString, artist.name))
result.toResult
}
def list() = Action.async { implicit request =>
EitherT(artistService.list()).toResult
}
}
开发者ID:FScoward,项目名称:billets-en-concert,代码行数:38,代码来源:ArtistController.scala
示例13: HolidayController
//设置package包名称以及导入依赖的类
package controllers
import play.api.data.Forms._
import play.api.data.Form
import play.api.data.validation.{Invalid, ValidationError, Valid, Constraint}
import play.api.mvc._
import views.html.{main,hellothere}
import models.HolidayData
class HolidayController extends Controller {
val nameConstraint : Constraint[String] = Constraint {field:String =>
field match {
case "" => Invalid("Required")
case x: String if !HolidayData.checkName(x) => Invalid("Not an employee")
case _ => Valid
}
}
val testForm = Form(
single("Name" -> text.verifying(nameConstraint))
)
def index = Action {
Ok(main(testForm))
}
def submit = Action { implicit request =>
testForm.bindFromRequest().fold(
(formWithErrors: Form[String]) => BadRequest(main(formWithErrors)),
name => Ok(hellothere(HolidayData.holidayRemaining(name)))
)
}
}
object HolidayController extends HolidayController
开发者ID:opencastsoftware,项目名称:holiday-tracker,代码行数:37,代码来源:HolidayController.scala
示例14: FormDataLogin
//设置package包名称以及导入依赖的类
package models
import dao.UserDao
import play.api.data.{Form, Mapping}
import play.api.data.Forms._
import play.api.data.validation.Constraints._
import play.api.data.validation.{Constraint, Invalid, Valid}
import scala.concurrent.Await
import scala.concurrent.duration.Duration
case class FormDataLogin(email: String, password: String)
case class FormDataAccount(name:String, email: String, password: String, passwordAgain:String)
object FormData {
val login = Form(
mapping(
"email" -> email,
"password" -> nonEmptyText
)(FormDataLogin.apply)(FormDataLogin.unapply)
)
val addMessage = Form(
mapping(
"content" -> nonEmptyText,
"tags" -> text
)(Message.formApply)(Message.formUnapply)
)
val uniqueEmail = Constraint[String] { email: String =>
val userFuture = UserDao.findByEmail(email)
Await.result(userFuture, Duration.Inf) match {
case Some(user) => Invalid("email already taken")
case None => Valid
}
}
private[this] def accountForm(passwordMapping:Mapping[String]) = Form(
mapping(
"name" -> nonEmptyText,
"email" -> email.verifying(maxLength(250), uniqueEmail),
"password" -> passwordMapping,
"passwordAgain" -> passwordMapping
)(FormDataAccount.apply)(FormDataAccount.unapply)
)
val updateAccount = accountForm(text)
val addAccount = accountForm(nonEmptyText)
}
开发者ID:asciiu,项目名称:polo,代码行数:54,代码来源:FormData.scala
示例15: Search
//设置package包名称以及导入依赖的类
package models
import models.utils.Util._
import play.api.libs.json.Json
import play.api.data._
import play.api.data.Forms._
import play.api.data.validation.{Constraint, Invalid, Valid}
case class Search(searchTerm: Option[String], searchValue: Option[String])
object Search {
implicit val formatter = Json.format[Search]
val searchTermEmptyConstraint: Constraint[Search] = Constraint({ model =>
model.searchTerm.getOrElse("").nonEmpty match {
case true => Valid
case false => Invalid("Name or email must be selected")
}
})
val searchValueEmptyConstraint: Constraint[Search] = Constraint({ model =>
model.searchTerm.isEmpty || (model.searchTerm.nonEmpty && model.searchValue.nonEmpty) match {
case true => Valid
case false if model.searchTerm.getOrElse("").equals("email") => Invalid("Email must not be empty")
case false if model.searchTerm.getOrElse("").equals("name") => Invalid("Name must not be empty")
}
})
val SearchForm = Form(
mapping(
"searchTerm" -> optional(text),
"searchValue" -> optional(text)
)
(Search.apply)(Search.unapply)
.verifying(searchTermEmptyConstraint)
.verifying(searchValueEmptyConstraint)
)
}
开发者ID:vinnicombe,项目名称:task-frontend,代码行数:39,代码来源:Search.scala
示例16: Person
//设置package包名称以及导入依赖的类
package models
import play.api.libs.json.Json
import play.api.data._
import play.api.data.Forms._
import play.api.data.validation.{Constraint, Invalid, Valid}
import utils.Util._
case class Person(name: Option[String], email: Option[String])
case class People(people: List[Person])
object Person {
implicit val formatter = Json.format[Person]
val nameEmptyConstraint: Constraint[Person] = Constraint({ model =>
model.name.nonEmpty match {
case true => Valid
case false => Invalid("Name field must not be empty")
}
})
val emailEmptyConstraint: Constraint[Person] = Constraint({ model =>
model.email.nonEmpty match {
case true => Valid
case false => Invalid("Email field must not be empty")
}
})
val emailInvalidConstraint: Constraint[Person] = Constraint({ model =>
model.email.isEmpty || (model.email.nonEmpty && model.email.getOrElse("").matches(emailRegex)) match {
case true => Valid
case false => Invalid("Email is invalid")
}
})
val PersonForm = Form(
mapping(
"name" -> optional(text),
"email" -> optional(text)
)
(Person.apply)(Person.unapply)
.verifying(nameEmptyConstraint)
.verifying(emailEmptyConstraint)
.verifying(emailInvalidConstraint))
}
object People {
implicit val formatter = Json.format[People]
}
开发者ID:vinnicombe,项目名称:task-frontend,代码行数:52,代码来源:Person.scala
注:本文中的play.api.data.validation.Invalid类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论