当前位置: 首页>>代码示例>>Scala>>正文


Scala Valid类代码示例

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


在下文中一共展示了Valid类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: Data

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

import play.api.data.Form
import play.api.data.Forms._
import play.api.data.validation.{ ValidationError, Invalid, Valid, Constraint }
import play.api.libs.json._
import play.api.libs.functional.syntax._


  case class Data(

    firstName: String,
    lastName: String,
    email: String,
    password: (String, String),
    description: String,
    age: Int
  )

  case class Password(
    password: String,
    passwordConfirmation: String
  )

} 
开发者ID:elarib,项目名称:cvManager,代码行数:26,代码来源:SignUpForm.scala

示例5: 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

示例6: 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

示例7: 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

示例8: 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

示例9: 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

示例10: SubscriptionController

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

import javax.inject.Inject

import model.Subscriber
import model.Subscriber._
import play.api.data.validation.{Constraints, Valid}
import play.api.libs.json.{JsSuccess, JsValue}
import play.api.mvc._
import services.OutboundService

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

class SubscriptionController @Inject()(out: OutboundService, cc: ControllerComponents) extends AbstractController(cc) {
  def add() = Action.async(parse.json) { implicit request: Request[JsValue] =>
    request.body.validate[Subscriber] match {
      case JsSuccess(sub, _) if isValidEmail(sub.email) =>
        out.publishNewSubscription(sub).map(_ => Ok("{}"))
      case JsSuccess(_, _) =>
        Future.successful(BadRequest("{'error': 'email value is not correct'}"))
      case _ =>
        Future.successful(BadRequest("{'error': 'json is malformed'}"))
    }
  }

  private def isValidEmail(email: String): Boolean = Constraints.emailAddress.apply(email) == Valid
} 
开发者ID:ScalaConsultants,项目名称:newspaper,代码行数:29,代码来源:SubscriptionController.scala

示例11: 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

示例12: 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.Valid类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。