0
votes

I am getting started with Play Framework, right now going through the Play's validation features. I tried to validate the form fields as shown in the below view model class.

public class ViewModel {

    @Required(message = "Please enter username")
    public String username;
    @Required(message = "Please enter the password")
    public String password;

}

Below is simple demo UI for the same.

enter image description here

Now, I would like to throw a global error message when entered username and password are incorrect when checked against the database.

Below is the code in my controller action

        Form<ViewModel> formData = Form.form(ViewModel.class).bindFromRequest();
        if (formData.hasErrors()) {
            Logger.info("There are server side validation errors in the form..");
            return badRequest(index.render(formData));
        } else {
           if(notFoundInDb){
             //check against db
             // some db related code here assuming record not found in db  
             ViewModel user = formData.get();
             //formData.error("invalid username and password");
             return badRequest(index.render(formData));
           }else{
             //success
             return redirect("/nextAction");
           }
    }

I have tried to use formData.error("invalid username and password");but not sure of this. In my view template to show global error message I used the following code.

@if(signIn.hasGlobalErrors) {
  <p>
       @signIn.globalError.message
  </p>
}

How to throw some nice global error message from controller action? I am using Play 2.4.2 version.

1

1 Answers

1
votes

You can use form.hasErrors, form.globalErrors, or form("singleElementName").errors to get validation errors of a form, e.g.

@if(form.hasErrors) {
  // Does form has any error, global or individual?
}
@for(error <- form.globalErrors) {
  // Global errors, use @error.message to get the message
}
@for(error <- form("singleElementName").errors) {
  // Individual error for a single form element, use @error.message
}