I am using Java Play 2.0.1 with both custom validation and the play.data.validation.constraints, and am looking for a means to display every error that occurs in the form regardless of whether my code is validating or if Play is.
What I am presently doing to display all errors, is I have a method in my Controller to add all of the errors contained within the Map retrieved from form.errors(), and then add them to the flash scope, which does the job in the sense that all errors will be detected, but not displayed on the first redirect until the play.data.validation errors are fixed.
public static void addFlashError(Map<String, List<ValidationError>> errors){
for(String key : errors.keySet()){
List<ValidationError> currentError = errors.get(key);
for(ValidationError error : currentError){
flash(key, error.message());
}
}
}
Then in my scala.html to display the errors
<div class="alert-message error">
@for((key, value) <- flash){
<strong>Error : </strong> @value<br />
}
</div>
But this does not seem to be the most simple solution, and Play does not display the custom validation errors at the same time as the play.data.validation errors, as it appears as though the play.data.validation errors are displayed, and then if there are none Play checks to see if there is a public String validate() contained in the class the form wraps.
Is there a simple approach to display all errors in the form, and not play.data.validation errors and then custom validation errors if the play.data.validation errors do not exist?
What I’ve done is to call
form.hasErrors()and store that value in a variable. Next you do all of your custom validation. Grabform.errors()(as you were doing) and if you find any errors then insert them directly into that map. If there were any validation errors then return with abadRequest()as usual passing in your Form instance (which contains the error map with all of the errors).