Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a custom validation error on a specific form field in Play! 2.*

Basically I have a following form class.

public static class BasicForm {
    @Required
    public String name;
    @Required
    @Email
    public String email;
    @Required
    public String password;
    @Required
    public String confirmPassword;

    public List<ValidationError> validate() {
        if (User.findByEmail(email) != null) {
            List<ValidationError> validationErrorList = new ArrayList<ValidationError>();
            validationErrorList.add(new ValidationError("email", "error.alreadyexists", new ArrayList<Object>()));
            return validationErrorList;
        }
        return null;
    }

}

As you can see, I am trying to validate the uniqueness of the email address. If email is not unique, I would like to display the error message on the email field, NOT as a global error message

What is the correct way of implementing validate() method to achieve this?

like image 770
iecanfly Avatar asked Jan 15 '23 13:01

iecanfly


2 Answers

You should use a validate method with the following signature:

public Map<String, List<ValidationError>> validate()

This way you can add errors to single fields like this:

Map<String, List<ValidationError>> errors = null;
if (emailIsBad) {
    errors = new HashMap<String, List<ValidationError>>();
    List<ValidationError> list = new ArrayList<ValidationError>();
    list.add(new ValidationError("email", "email is bad"));
    errors.put("email", list);
}
return errors;

please note that if you should return an empty map, it still will render the form as erroneous. If you want the validate() method to succeed, you need to return null.

like image 116
Daniel Avatar answered Jan 20 '23 15:01

Daniel


Not enough rep to comment (yet), but don't forget to include the proper import statement:

import.play.data.validation.*;

I wasted a few minutes due to an incorrect statement.

like image 36
Shanker Kaura Avatar answered Jan 20 '23 15:01

Shanker Kaura