简体   繁体   中英

How to Set custom error message on Play2-Scala 2.4 controller

I want to set custom error message, validation.

This is my controller action method Play2-scala 2.4 application

val myForm1 = Form (
  mapping(
    "hoge" -> Forms.text.verifying("req!", { !_.isEmpty() }),
    "piyo" -> Forms.number.verifying("1 to 10", n => { n >= 1 && n <= 10 })
)(MyFormRequest.MyParams1.apply)(MyFormRequest.MyParams1.unapply))
def validator1 = Action {
  Ok(views.html.myformrequest.validator1(myForm1))
}
def check1 = Action { implicit request =>
  val form = myForm1.bindFromRequest()
  if (!form.hasErrors) {
    val myParams1 = form.get
    Ok("check1 ok hoge: " + myParams1.hoge + " piyo: " + myParams1.piyo)
  } else {
    Ok("check1 ng " + form.error("piyo").get.message)
  }
}

here

"piyo" -> Forms.number.verifying("1 to 10", n => { n >= 1 && n <= 10 })

I use "verifying" method. I can set custom message for "1 <= n <= 10" condition. OK.

But I cannot set message for "number" condition. When input "abc" in piyo parameter, error message is just "error.number".

"Forms.number" method don't have parameter for setting error message.

How to set custom error message for "Forms" members(text, number, boolean, date, email....)

As far as I can tell, you can not have two verifying expressions on a form field. You could however add one more condition to check that n is a number.

So:

n => { n >= 1 && n <= 10 && n.isInstanceOf[Int]}

As far as custom error messages, You can define a custom message in the messages conf file. You can adapt the examples from the Play! website to your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM