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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With