在Struts2中结合Validate Method和xml验证 [英] Combining Validate Method and xml validation in Struts2

查看:110
本文介绍了在Struts2中结合Validate Method和xml验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将xml验证和Validate方法结合起来进行表单验证?



我的一般想法是,xml验证将主要包含给定字段名称的长度,它是一个数字,它是一个有效的电子邮件地址?虽然Validate方法将检查给定的字段名值,如果该值存在于数据库中,那么会出错。



如果需要,请显示一个示例。

解决方案

AFAIK,no。根据评论,是的。 p>我一直认为验证是为了验证输入的正确性,而不是语义:如果输入错误,返回;如果输入无误,请在db上检查重复项,检查用户角色的权限,调用服务,查看文件系统等。



顺便提一句,请注意: fieldexpression validator ,你可以用参数调用函数,就像在JSP中一样(它是OGNL)。



很可能是一种不好的做法(请参阅上文),但您可以这样做:

 <校验> 
< field name =username>
< field-validator type =fieldexpression>
< param name =expression>
<![CDATA [
isUserAlreadyInDatabase(username)
]]>
< / param>
< message>功能呼叫讯息在这里< / message>
< / field-validator>
< / field>
< /验证器>

我已经分享了这个,因为它值得了解,在某些情况下它可能非常有用(绝对不是你的问题指出的那个)。



例如,我用它来检查页面的日期是否在当前主题的startDate和endDate之间。 startDate和endDate是来自Action的实例变量,通过getters读取...



阅读此链接:我们可以用Struts2中的参数调用方法吗?



希望可以帮助


Is it possible to combine both xml validation and Validate method for form validation?

my general thought is that the xml validation will just mostly contain how long should a given field name is, is it a digit, is it a valid email address?. While the Validate method will check a given fieldname value if that value exist in the database it would then an error.

if so please show an example.

解决方案

AFAIK, no. According to comments, yes.

I've always thought that Validation is intended to validate the correctness of the input, not the "semantic": If input is wrong, go back; if input is fine, check on db for duplicates, check user roles for permissions, call services, look into file system, etc.

By the way, note this: with fieldexpression validator, you can call functions with parameters, like in JSP (it is OGNL).

It would be probably a bad practice (read above), but you could do something like this:

<validators>
    <field name="username">
        <field-validator type="fieldexpression">
            <param name="expression">
                <![CDATA[
                    isUserAlreadyInDatabase(username)
                ]]>
            </param>
            <message>function call message here</message>
        </field-validator>
    </field>
</validators>

I've shared this because it is worth knowing and it can be really useful in some cases (definitely not the one pointed out by your question).

For example i used this to check if Dates from page were in the interval betweeen startDate and endDate of the current Subject. startDate and endDate was instance variables from the Action, read through getters...

Read this link too: Can we call methods with parameters in Struts2 fieldexpression?

Hope that helps

这篇关于在Struts2中结合Validate Method和xml验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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