Reputation: 18918
I am trying to catch validation errors when submitting a POST request via an HTML form. I have the following code in my Application.java
class:
public class Application extends Controller
{
..
public static Result addSubscriber()
{
Form<Subscriber> subscriberForm = Form.form(Subscriber.class);
subscriberForm.bindFromRequest();
Logger.warn(subscriberForm.toString());
if (!(subscriberForm.hasErrors() || subscriberForm.hasGlobalErrors()))
{
Logger.error("dammit");
}
else // never reaches here
...
}
}
And in my Subscriber.java
class:
@Entity
public class Subscriber extends Model
{
@Id
public String email;
@CreatedTimestamp
Timestamp createdAt;
...
public List<ValidationError> validate()
{
List<ValidationError> errors = new ArrayList<ValidationError>();
Pattern p = Pattern.compile("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$");
Matcher m = p.matcher(email);
if (!m.find())
{
Logger.error("\"" + email + "\" appears to be an invalid email.");
errors.add(new ValidationError("email", "\"" + email + "\" appears to be an invalid email."));
}
if (Subscriber.exists(email))
{
Logger.error("\"" + email + "\" is already subscribed!");
errors.add(new ValidationError("subscribed", "\"" + email + "\" is already subscribed!"));
}
Logger.warn("whoa!!!!!! " + errors.toString());
//return errors.isEmpty() ? null : errors;
return errors;
}
}
The result when I try entering an invalid email:
[error] application - "wofutn@nufwu" appears to be an invalid email.
[warn] application - whoa!!!!!! [ValidationError(email,"wofutn@nufwu" appears to be an invalid email.,[])]
[warn] application - Form(of=class models.Subscriber, data={}, value=None, errors={})
[error] application - dammit
Why is the error list empty?! As far as I can tell I am following directions. I can't seem to trigger errors no matter what.
I am using Play 2.2.2 so this appears to be the relevant source code file. I don't immediately see what I'm doing wrong though.
Upvotes: 0
Views: 56
Reputation: 14411
The bindFromRequest() method doesn't mutate an object but returns a new instance of a form. In other words your errors are not assigned to anything because you work on object before validation is applyed. Simply change it as follows to fix the issue.
Form<Subscriber> subscriberForm = Form.form(Subscriber.class);
subscriberForm = subscriberForm.bindFromRequest();
Upvotes: 1