本文整理汇总了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())
}
}
}
示例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)
)
}
示例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))
}
}
}
示例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
)
}
示例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
}
}
示例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")))
}
}
}
示例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))
}
}
}
示例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
示例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)
}
示例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
}
示例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)
)
}
示例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]
}