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


Scala FormError类代码示例

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


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

示例1: FieldMappingsSpec

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentmappingfrontend.controllers

import org.scalatest.EitherValues
import play.api.data.FormError
import uk.gov.hmrc.play.test.UnitSpec

class FieldMappingsSpec extends UnitSpec with EitherValues {
  "utr bind" should {
    val utrMapping = utr.withPrefix("testKey")

    def bind(fieldValue: String) = utrMapping.bind(Map("testKey" -> fieldValue))

    "accept valid UTRs" in {
      bind("2000000000") shouldBe Right("2000000000")
    }

    "give \"error.required\" error when it is not supplied" in {
      utrMapping.bind(Map.empty).left.value should contain only FormError("testKey", "error.required")
    }

    "give \"error.required\" error when it is empty" in {
      bind("").left.value should contain only FormError("testKey", "error.required")
    }

    "give \"error.required\" error when it only contains a space" in {
      bind(" ").left.value should contain only FormError("testKey", "error.required")
    }

    "give \"error.utr.invalid\" error when it is invalid" in {
      bind("20000000000").left.value should contain only FormError("testKey", "error.utr.invalid")
    }
  }

  "arn bind" should {
    val arnMapping = arn.withPrefix("testKey")

    def bind(fieldValue: String) = arnMapping.bind(Map("testKey" -> fieldValue))

    "accept valid ARN" in {
      bind("TARN0000001") shouldBe Right("TARN0000001")
    }

    "give \"error.required\" error when it is not supplied" in {
      arnMapping.bind(Map.empty).left.value should contain only FormError("testKey", "error.required")
    }

    "give \"error.required\" error when it is empty" in {
      bind("").left.value should contain only FormError("testKey", "error.required")
    }

    "give \"error.required\" error when it only contains a space" in {
      bind(" ").left.value should contain only FormError("testKey", "error.required")
    }

    "give \"error.arn.invalid\" error when it is invalid" in {
      bind("ARN0000001").left.value should contain only FormError("testKey", "error.arn.invalid")
    }
  }
} 
开发者ID:hmrc,项目名称:agent-mapping-frontend,代码行数:60,代码来源:FieldMappingsSpec.scala

示例2: enumFormat

//设置package包名称以及导入依赖的类
package com.github.stonexx.play.data.formats

import com.github.stonexx.scala.data.OrderedEnumeration
import com.github.stonexx.scala.util.string._
import play.api.data.FormError
import play.api.data.format.Formatter

trait EnumFormats {

  def enumFormat[E <: Enumeration](
    parse: String => E#Value,
    serialize: E#Value => String,
    error: (String, Throwable) => Seq[FormError]
  ): Formatter[E#Value] = new Formatter[E#Value] {
    def bind(key: String, data: Map[String, String]): Either[Seq[FormError], E#Value] =
      play.api.data.format.Formats.stringFormat.bind(key, data).right.flatMap { s =>
        scala.util.control.Exception.allCatch[E#Value].either(parse(s)).left.map(error(key, _))
      }

    def unbind(key: String, value: E#Value) = Map(key -> serialize(value))
  }

  def enumIdFormat[E <: Enumeration](enum: E): Formatter[E#Value] = enumFormat(
    s => enum(s.toInt), _.id.toString,
    (key, _) => Seq(FormError(key, "error.enum.id", Nil))
  )

  def enumNameFormat[E <: Enumeration](enum: E): Formatter[E#Value] = enumFormat(
    s => enum.values.find(_.toString.camelToUnderscore == s.camelToUnderscore).get, _.toString,
    (key, _) => Seq(FormError(key, "error.enum.name", Nil))
  )

  def enumOrderedFormat[E <: OrderedEnumeration](enum: E): Formatter[E#Ordered] = new Formatter[E#Ordered] {
    def bind(key: String, data: Map[String, String]): Either[Seq[FormError], E#Ordered] =
      play.api.data.format.Formats.stringFormat.bind(key, data).right.flatMap { s =>
        scala.util.control.Exception.allCatch[E#Ordered].either(enum.Ordered.parse(s))
          .left.map(_ => Seq(FormError(key, "error.sort", Seq(s))))
      }

    def unbind(key: String, value: E#Ordered) = Map(key -> value.toString)
  }
} 
开发者ID:stonexx,项目名称:utils,代码行数:43,代码来源:EnumFormats.scala

示例3: ExtendedForm

//设置package包名称以及导入依赖的类
package it.agilelab.bigdata.wasp.web.forms

import play.api.data.Form
import play.api.data.FormError
import play.api.data.Mapping

case class ExtendedForm[T](mapping : Mapping[T], extendedValidation : Form[T] => Seq[(String, String)]) {
  def bind(data : Map[String, String]) : Form[T] = evaluateAdditionalErrors(form.bind(data))
  def bind(data : play.api.libs.json.JsValue) : Form[T] = evaluateAdditionalErrors(form.bind(data))
  def bindFromRequest()(implicit request : play.api.mvc.Request[_]) : Form[T] = evaluateAdditionalErrors(form.bindFromRequest())
  def bindFromRequest(data : Map[String, Seq[String]]) : Form[T] = evaluateAdditionalErrors(form.bindFromRequest(data))

  def evaluateAdditionalErrors(form : Form[T]) = {
    val additionalErrors = extendedValidation(form).map(t => FormError(t._1, t._2))
    val addedKeys = additionalErrors.map(e => e.key).toSet
    val overwrittenErrors = form.errors.filter(e => addedKeys.contains(e.key))

    Form(form.mapping, form.data, form.errors.diff(overwrittenErrors) ++ additionalErrors, form.value)
  }

  protected val form = Form(mapping, Map(), Nil, None)
} 
开发者ID:agile-lab-dev,项目名称:wasp,代码行数:23,代码来源:ExtendedForm.scala

示例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))
      }
    }

} 
开发者ID:PeterPerhac,项目名称:pocs,代码行数:61,代码来源:ValidationUtils.scala

示例5: VehiclesControllerSpec

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

import play.api.data.FormError
import play.api.mvc.Controller
import play.api.test.{PlaySpecification, WithApplication, FakeRequest}
import repositories.VehiclesFakeRepository

class VehiclesControllerSpec extends PlaySpecification {
  trait Context extends Controller with VehiclesController {
    def vehiclesRepository = new VehiclesFakeRepository {}
  }

  "Vehicles controller" should {
    "present search" in new WithApplication with Context {
      val result = searchPrompt(FakeRequest())
      status(result) mustEqual OK
    }

    "give details of a vehicle" in new WithApplication with Context {
      val result = search(FakeRequest().withFormUrlEncodedBody("registration" -> vehiclesRepository.ford.registration,
                                                               "make" -> vehiclesRepository.ford.make))
      status(result) mustEqual OK
    }
  }

  "Vehicles form" should {
    "read from request" in new WithApplication with Context {
      val formBinding = form.bind(Map("registration" -> "BLAH", "make" -> "BLAH")) // TODO Validations e.g. PP is not a valid registration.

      formBinding.get mustEqual ("BLAH", "BLAH")
    }

    "give errors for missing data" in new WithApplication with Context {
      val formBinding = form.bind(Map.empty[String, String])

      formBinding.errors must contain(exactly(FormError("registration", "error.required"), FormError("make", "error.required")))
    }
  }
} 
开发者ID:davidainslie,项目名称:voa-test,代码行数:40,代码来源:VehiclesControllerSpec.scala

示例6: validate

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

import library.exception.validation.{ErrorDetail, ValidationException}
import play.api.data.{Form, FormError}
import play.api.mvc.Request


  @SuppressWarnings(Array("org.wartremover.warts.ImplicitParameter"))
  def validate[A](form: Form[A])(implicit request: Request[_]): A = {
    form.bindFromRequest.fold(
      formWithErrors => {
        throw new ValidationException(convertErrors(formWithErrors))
      },
      validObject => validObject
    )
  }

  private def convertErrors[A](formWithErrors: Form[A]): Seq[ErrorDetail] = {
    formWithErrors.errors.map { error =>
      ErrorDetail(createMessage(error), ValidationExceptionCode)
    }
  }

  private def createMessage(formError: FormError): String = {
    Map(
      "key" -> formError.key,
      "detail" -> s"${formError.message}${formError.args.mkString("(", ", ", ")")}"
    ).mkString("{", ", ", "}")
  }

  private val ValidationExceptionCode = "ValidationException"
} 
开发者ID:tmknom,项目名称:heavens-door,代码行数:33,代码来源:FormValidation.scala

示例7: DashboardSettingsForms

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

import javax.inject.{Inject, Singleton}

import com.cobble.bot.common.models.{CustomCommand, FilterSettings}
import com.cobble.bot.common.ref.{MtrConfigRef, MessageRef}
import play.api.data.{Form, FormError}
import play.api.data.Forms._

@Singleton
class DashboardSettingsForms @Inject()(mtrConfigRef: MtrConfigRef) {

    val filterForm: Form[FilterSettings] = Form(
        mapping(
            "guildId" -> ignored(mtrConfigRef.guildId),
            "capsFilterEnabled" -> boolean,
            "capsFilterExemptionLevel" -> number,
            "capsFilterThreshold" -> number(min = 1, max = 100),
            "linksFilterEnabled" -> boolean,
            "linksFilterExemptionLevel" -> number,
            "blacklistFilterEnabled" -> boolean,
            "blacklistFilterExemptionLevel" -> number,
            "blacklistFilterWords" -> text
        )(FilterSettings.apply)(FilterSettings.unapply)
    )

    val commandForm: Form[CustomCommand] = Form(
        mapping(
            "guildId" -> ignored(mtrConfigRef.guildId),
            "commandName" -> nonEmptyText,
            "permissionLevel" -> number,
            "commandContent" -> nonEmptyText(maxLength = MessageRef.TWITCH_MAX_MESSAGE_LENGTH_USABLE)
        )(CustomCommand.apply)(CustomCommand.unapply)
    )

    val deleteCommandForm = Form(
        single(
            "commandName" -> nonEmptyText
        )
    )

    val existingCommandFormError: FormError = FormError("commandName", "dashboard.forms.customCommands.newCommand.errors.commandExists")

} 
开发者ID:Cobbleopolis,项目名称:MonsterTruckBot,代码行数:45,代码来源:DashboardSettingsForms.scala

示例8: Utils

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

import java.util.Date
import play.api.data.format._
import play.api.data.FormError
import play.api.data.Forms._
import play.api.data.Mapping
import views.html.helper.FieldConstructor

object Utils {
  type Range[A] = (Option[A], Option[A])  
  
  case class Param(
    name: Option[String],
    birth: Range[Date],
    height: Range[Int],
    weight: Range[Int],
    bust:   Range[Int],
    waist:  Range[Int],
    hip:    Range[Int],
    cup:    Range[Char]
  ) {
    def birth_sql = birth match {
      case (Some(from), Some(to)) => (Some(new java.sql.Date(from.getTime)), Some(new java.sql.Date(to.getTime)))
      case (None,       Some(to)) => (None,                                  Some(new java.sql.Date(to.getTime)))
      case (Some(from), None)     => (Some(new java.sql.Date(from.getTime)), None)
      case (None,       None)     => (None, None)
    }
  }

  private implicit def charFormat: Formatter[Char] = new Formatter[Char] {
    def bind(key: String, data: Map[String, String]) =
      data.get(key).filter(s => s.length == 1 && s != " ").map(s => Right(s.charAt(0))).getOrElse(
        Left(Seq(FormError(key, "error.required", Nil)))
      )
    def unbind(key: String, value: Char) = Map(key -> value.toString)
  }
  val char = of[Char]

  implicit val fieldConstructor = FieldConstructor(views.html.fieldConstructor.f)
} 
开发者ID:skobaken7,项目名称:idle_search,代码行数:42,代码来源:Utils.scala


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