How can I show a validation error for a form field outside of a field constructor in Play framework 2? Here is what I tried:
@eventForm.("name").error.message
And I get this error:
value message is not a member of Option[play.api.data.FormError]
I’m confused because in the api docs it says message is a member of FormError. Also this works fine for global errors:
@eventForm.globalError.message
You can get a better grasp of it checking Form’s sourcecode here
Formdefines an apply method:That, as said in the doc, returns any field, even if it doesn’t exist. And a
Fieldhas anerrorsmember which returns aSeq[FormError]:So, you could do something like that (for the
Seq[FormError]):Or (for the
Option[FormError])Or, you could use
Formerrors:And get all errors of a given key. Like this (for the
Seq[FormError]):Or (for the
Option[FormError])If you want more details, check the source code. It’s well written and well commented.
Cheers!
EDIT:
As biesior commented: to show human readable pretty messages with different languages you have to check how play works I18N out here
To be thorough you’re probably going to have to deal with I18N. It’s not hard at all to get it all working.
After reading the documentation you may still find yourself a bit consufed. I’ll give you a little push. Add a
messagesfile to yourconffolder and you can copy its content from here. That way you’ll have more control over the default messages. Now, in your view, you should be able to do something like that:For instance, if
error.messagewereerror.invalidit would show the message previously defined in theconf/messagesfileInvalid value.argsdefine some arguments that your error message may handle. For instance, if you were handling anerror.min, anargcould be the minimum value required. In your message you just have to follow the{n}pattern, where n is the order of your argument.Of course, you’re able to define your own messages like that:
And in your controller you could check your form like that (just one line of code to show you the feeling of it)
If you want to play around with languages, just follow the documentation.
Cheers, again!