First of all I want to state that I think that the Play documentation for 2.0 is really, really bad.
I\'m looking for a way to place a validation error underneath a HTML
I use this code to display a global bootstrap alert box with on the form:
@if(form.hasErrors) {
<div class="alert alert-error">
<a class="close" data-dismiss="alert">x</a>
@if(form.errors.size() > 0) {
@for((key, value) <- form.errors) {
@key.toString() :
@for(err <- value) {
@err.message().toString()
}
}
} else {No error returned.}
</div>
}
The output for an form error key-value pair is a bootstrap alert box with @key.toString() : @value.message.toString
.
If you wanted to display the error at the field level instead, you would want to modify it slightly with another conditional statement for the form.errors map value so that it only triggered for the specific field. I haven't tested this, but it'd go something like:
@if(form.hasErrors) {
@if(form.errors.size() > 0) {
@for((key, value) <- form.errors) {
@for(err <- value) {
@if(err.contains("YourSelectFieldName")) {
@err.message().toString()
}
}
}
}
}
The answer from 2manyprojects works very well but you can do the same thing in the controller. It all depends on your preference and style.
public static Result save() {
Form<form> boundForm = form.bindFromRequest();
if (boundForm.hasErrors()) {
String errorMsg = "";
java.util.Map<String, List<play.data.validation.ValidationError>> errorsAll = boundForm.errors();
for (String field : errorsAll.keySet()) {
errorMsg += field + " ";
for (ValidationError error : errorsAll.get(field)) {
errorMsg += error.message() + ", ";
}
}
flash("error", "Please correct the following errors: " + errorMsg);
return badRequest(detail.render(boundForm));
}