How to set a custom validation error in a separate form field on Play! 2. *

Basically, I have the 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 verify the uniqueness of an email address. If the email address is not unique, I would like to display the error message in the email field, and not as a global error message

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

+4
source share
3 answers

You must use the validate method with the following signature:

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

Thus, you can add errors to single fields as follows:

 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; 

note that if you must return a blank card, it will still make the form erroneous. If you want the validate() method to succeed, you need to return null.

+8
source

There are not enough comments for comments (for now), but be sure to include the correct import statement:

 import.play.data.validation.*; 

I spent a few minutes due to an incorrect statement.

+1
source

Here's what I came up with on the basis of Daniel's code: My code checks for password confirmation, tho.

 public Map<String, List<ValidationError>> validate() { Map<String, List<ValidationError>> errors = null; if (!password.equals(confirmPassword)) { errors = new HashMap<>(); List<ValidationError> list = new ArrayList<>(); list.add(new ValidationError("password", "Passwords do not match")); errors.put("password",list); errors.put("confirmPassword", list); } return errors; } 
0
source

Source: https://habr.com/ru/post/1433979/


All Articles