如何在JSF-Page中使用validateRegex验证数字字段? [英] How validate number fields with validateRegex in a JSF-Page?

查看:153
本文介绍了如何在JSF-Page中使用validateRegex验证数字字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在托管bean中,我具有int类型的属性.

In a managed bean I have a property of the type int.

@ManagedBean
@SessionScoped
public class Nacharbeit implements Serializable {

private int number;

在JSF页面中,我尝试验证此属性仅用于6位数字输入

In the JSF page I try to validate this property for 6 digits numeric input only

               <h:inputText id="number"
                         label="Auftragsnummer"
                         value="#{myController.nacharbeit.number}"
                         required="true">
                <f:validateRegex pattern="(^[1-9]{6}$)" />
            </h:inputText>

在运行时出现异常:

javax.servlet.ServletException: java.lang.Integer cannot be cast to java.lang.String

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

正则表达式错了吗?还是ValidateRegex仅用于字符串?

Is the regex wrong? Or are the ValidateRegex only for Strings?

推荐答案

The <f:validateRegex> is intented to be used on String properties only. But you've there an int property for which JSF would already convert the submitted String value to Integer before validation. This explains the exception you're seeing.

但是,由于您已经在使用int属性,因此当您输入非数字字符时,您将已经收到转换错误.转换错误消息可以通过converterMessage属性进行配置.因此,您根本不需要使用正则表达式.

But as you're already using an int property, you would already get a conversion error when you enter non-digits. The conversion error message is by the way configureable by converterMessage attribute. So you don't need to use regex at all.

对于具体的功能要求,您似乎想验证最小/最大长度.为此,您应该使用 <f:validateLength> .将此属性与maxlength属性结合使用,以使最终用户无论如何都不能输入超过6个字符.

As to the concrete functional requirement, you seem to want to validate the min/max length. For that you should be using <f:validateLength> instead. Use this in combination with the maxlength attribute so that the enduser won't be able to enter more than 6 characters anyway.

<h:inputText value="#{bean.number}" maxlength="6">
    <f:validateLength minimum="6" maximum="6" />
</h:inputText>

您可以通过validatorMessage配置验证错误消息.因此,所有这些可能看起来像这样:

You can configure the validation error message by the validatorMessage by the way. So, all with all it could look like this:

<h:inputText value="#{bean.number}" maxlength="6"
    converterMessage="Please enter digits only."
    validatorMessage="Please enter 6 digits.">
    <f:validateLength minimum="6" maximum="6" />
</h:inputText>

这篇关于如何在JSF-Page中使用validateRegex验证数字字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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