I just started with Play and am trying to get some custom constraints on my model.
I have found that this works
@Constraints.Required
@Constraints.MaxLength(15)
@Constraints.MinLength(4)
@Constraints.Pattern(value = "^\\w\\s$")
public String username;
But now I want to add a custom constraint with an own implementation (for checking for uniqueness) So I tried this (it was auto-completed by my IDE so it does exist)
@Constraints.ValidateWith(Account.UniqueValidator.class)
public String username;
I found somewhere (have gone through a lot of links so can't find it anymore, that the class should extend Constraints.Validator
So that is what I did.
private class UniqueValidator extends Constraints.Validator<String>
{
@Override
public boolean isValid(String s) {
return Account.find.where().eq("username", s).findRowCount() == 0;
}
@Override
public F.Tuple<String, Object[]> getErrorMessageKey() {
return null;
}
}
However I don't know what to return in the getErrorMessageKey value, it is a required method to implement. I looked in the play source and I found "something" what looks like this. Namely the NotEmpty validator.
However when you look there you see it returns an Tuple, not an F.Tuple. When I change that in my code it complains that it is not an F.Tuple.
Tried to return
return Tuple("error.invalid", new Object[] {});
As done in the NotEmpty validator link above. But than it says that it needs "new" before Tuple, but that gives me an class with a bunch of required methods to implement. So I guess that is not really the way to go.
When I look at the documentation of play here I need to use the @CheckWith annotation, but when I choose that it says that it cannot find the @CheckWith annotation.
I am lost. :-)
Note that F.Tuple
is a template type which requires two template arguments, but in the return
statement that you tried, you did not specify any template arguments.
In order to make your code work, simply change the line
return Tuple("error.invalid", new Object[] {});
to
return new Tuple<String, Object[]>("error.invalid", new Object[] {});
Alternatively, you could write
return F.Tuple("error.invalid", new Object[] {});
In this statement, F.Tuple
is a static factory method which constructs and returns a Tuple
with the correct template arguments.
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