2014-09-03 143 views
0

我想通过HTML表单提交POST请求时发现验证错误。我在我的Application.java类下面的代码:播放框架无法识别错误?

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 
     ... 
    } 
} 

在我Subscriber.java类:

@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_.+-][email protected][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; 
    } 
} 

当我尝试输入无效的电子邮件结果:

[error] application - "[email protected]" appears to be an invalid email. 
[warn] application - whoa!!!!!! [ValidationError(email,"[email protected]" appears to be an invalid email.,[])] 
[warn] application - Form(of=class models.Subscriber, data={}, value=None, errors={}) 
[error] application - dammit 

为什么错误列表为空?据我可以告诉I am following directions。无论如何,我似乎无法触发错误。

我使用Play 2.2.2 so this appears to be the relevant source code file。尽管我没有立即看到我在做什么错误。

回答

1

bindFromRequest()方法不改变对象,但返回一个窗体的新实例。换句话说,你的错误没有分配给任何东西,因为你在应用验证之前处理对象。只需将其更改为以下问题即可解决问题。

Form<Subscriber> subscriberForm = Form.form(Subscriber.class); 
subscriberForm = subscriberForm.bindFromRequest(); 
+0

终于!非常感谢 :) – wrongusername 2014-09-03 16:13:40