本文整理汇总了Scala中play.api.data.validation.Constraint类的典型用法代码示例。如果您正苦于以下问题:Scala Constraint类的具体用法?Scala Constraint怎么用?Scala Constraint使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Constraint类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: 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))
}
}
}
示例5: 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
)
}
示例6: 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
示例7: 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)
}
示例8: 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)
)
}
示例9: 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]
}