如何在JSF表单上验证模式的字符串输入字段 [英] how to validate string input field for pattern on JSF form

查看:52
本文介绍了如何在JSF表单上验证模式的字符串输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,其中接受字符串的输入字段只能具有以下一种格式,使用javascript或jsf验证程序实现此功能的最佳方法是什么:

i have a requirement where a input field which takes strings can have only one of these formats, what is the best way to implement this using javascript or jsf validator:

N/A-N-N-N或N/A-N-N-N-N

N/A-N-N-N or N/A-N-N-N-N

上面的模式可以用任何字母代替A.上面的模式可以用任何数字代替N,而不是0.

There can be any alphabet in pattern above in place of A. there can be any numeric in pattern above in place of N other than 0.

推荐答案

首先,没有最佳"方法.只有正确"的方式取决于具体的功能要求.

First of all, there is no "best" way. There's just the "right" way which depends on the concrete functional requirements.

在JSF中进行验证的通常方法是使用创建一个实现Validator接口的类(如果标准标记中没有所需的功能).一种替代方法是按照您自己的建议通过JavaScript进行验证,但这完全破坏了服务器的健壮性,侧面验证,因为JavaScript代码受最终用户完全控制,因此最终用户可对其进行编辑/伪造/禁用.

The normal approach to validate in JSF is to use one of the standard validators available via <f:validateXxx> tags, or to create a class which implements the Validator interface if the desired functionality is not available in the standard tags. An alternative would be to validate by JavaScript as you suggested yourself, but this completely defeats the robustness of server-side validation because JavaScript code is under full control by the enduser and thus editable/spoofable/disablable by the enduser.

在特定情况下,您想验证输入是否与常规模式匹配.在这种情况下,<f:validateRegex>因此是该作业的正确标记.

In your particular case, you want to validate the input whether it matches a regular pattern. In that case, the <f:validateRegex> is thus the right tag for the job.

对于实际的常规模式,1到9之间的任何数字都用[1-9]表示的正则表达式,而A和Z之间的任何字母字符都用[A-Z]表示的正则表达式(区分大小写!如果您打算允许小写,同样,请使用[a-zA-Z]).像最后一个数字一样的任何零或一次出现"都用(...)?表示的正则表达式中,其中...将用实际模式替换.其余的字符/-可以按原样表示,只要它们不是正则表达式中的特殊字符(例如.(等),否则就需要使用\进行转义.

As to the actual regular pattern, any number between 1 and 9 is in regex represented by [1-9] and any alphabetic character between A and Z is in regex represented by [A-Z] (case sensitive! if you intend to allow lowercase as well, use [a-zA-Z]). Any "zero or one occurrence" like as the last number is in regex represented by (...)? whereby the ... is to be substituted with the actual pattern. The remainder, the characters / and - can be represented as-is as long as those are no special characters in regex such as ., (, etc, otherwise they needs to be escaped with \.

因此,总而言之,这应该做到:

So, all in all, this should do:

<h:inputText>
    <f:validateRegex pattern="[1-9]/[A-Z]-[1-9]-[1-9]-[1-9](-[1-9])?" />
</h:inputText>

另请参见:

  • Regex教程
  • java.util.regex.Pattern javadoc
  • See also:

    • Regex tutorial
    • java.util.regex.Pattern javadoc
    • 这篇关于如何在JSF表单上验证模式的字符串输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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