Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

regex - How validate number fields with validateRegex in a JSF-Page?

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

@ManagedBean
@SessionScoped
public class Nacharbeit implements Serializable {

private int number;

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>

On runtime I get an exception:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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>

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...