为什么不在模板中显示Playframework自定义验证消息 [英] Why isn't Playframework custom validation message not displayed in template

查看:86
本文介绍了为什么不在模板中显示Playframework自定义验证消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用play框架执行一些自定义验证,但我似乎无法从模板中获得错误。

控制器代码是:

  
User user = User.findByEmail(email);

if(user!= null){
Logger.warn(用户帐户已经为电子邮件%s创建,email);
validation.addError(email,此电子邮件地址已被使用。);
params.flash();
flash.error(请更正下面的错误!);
注册();
}

和signup.html模板:

#{error'email'/} 

我可以看到控制器看到重复的电子邮件,但该错误消息不会出现在模板中。



上面的代码是正确的吗? 因为你要去到另一个视图(即您重定向回注册视图),Play执行重定向,这意味着错误不再在范围内,因为注册视图被视为新请求。

$ b $为了解决这个问题,您需要保持验证消息可用于下一个请求,这通过使用 validation.keep()来实现。因此,在你调用 signup()之前,改变你的代码,你可以调用 validation.keep()



您的代码应该看起来像

< pre $ if(user!= null){
Logger.warn(用户帐户已经为电子邮件%s创建,email);
validation.addError(email,此电子邮件地址已被使用。);
params.flash();
flash.error(请更正下面的错误!);
validation.keep();
注册();
}


I am trying to perform some custom validation with play framework but I don't seem to be able to get the error from the template.

The controller code is :


        User user = User.findByEmail(email);

        if(user != null) {
            Logger.warn("User account already created for email %s", email);
            validation.addError("email", "This email address already in use.");
            params.flash();
            flash.error("Please correct the error below!");
            signup();
        }

and the signup.html template:

#{error 'email' /}

I can see that the controller sees the duplicate email but the error message does not appear in the template.

Is the code above correct?

解决方案

Because you are going to a different view (i.e. you are redirecting back to the signup view), Play performs a redirect, which means that the errors are no longer in scope, as the signup view is treated as a new request.

To get around this, you need to keep the validation messages available for the next request, which is achieved by using the validation.keep() function.

So, change your code, so that just before you call signup(), you call validation.keep().

Your code should look like

if(user != null) {
    Logger.warn("User account already created for email %s", email);
    validation.addError("email", "This email address already in use.");
    params.flash();
    flash.error("Please correct the error below!");
    validation.keep();
    signup();
}

这篇关于为什么不在模板中显示Playframework自定义验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆