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

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?

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>

You can achieve this without regex also
To validate int values:
<h:form id="user-form">
<h:outputLabel for="name">Provide Amount to Withdraw </h:outputLabel><br/>
<h:inputText id="age" value="#{user.amount}" validatorMessage="You can Withdraw only between $100 and $5000">
<f:validateLongRange minimum="100" maximum="5000" />
</h:inputText><br/>
<h:commandButton value="OK" action="response.xhtml"></h:commandButton>
</h:form>
To validate float values:
<h:form id="user-form">
<h:outputLabel for="amount">Enter Amount </h:outputLabel>
<h:inputText id="name-id" value="#{user.amount}" validatorMessage="Please enter amount between 1000.50 and 5000.99">
<f:validateDoubleRange minimum="1000.50" maximum="5000.99"/>
</h:inputText><br/><br/>
<h:commandButton value="Submit" action="response.xhtml"></h:commandButton>
</h:form>

Related

How to validate numeric strings in inputText with validateRegex in a JSF-Page

I have a managed bean with this string property
private String itemNumber;
In the JSF I want to validate the input for length of 10 characters and allow only digits. The input will have preceding zeros. For example "0000123456"
<h:inputText value="#{testBean.itemNumber}">
<f:validateRegex pattern="\d\d\d\d\d\d\d\d\d\d" />
</h:inputText>
On input of "asdf123456' I will get an beatiful validation message.
But on input of "0000123456" I will get this exception
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
What is wrong? Any ideas?
Declare the variable in the backing bean that is bound to your input text field as Integer/Long/BigDecimal and use
<f:validateLength maximum="10" minimum="10" />
instead of <f:validateRegex pattern="\d\d\d\d\d\d\d\d\d\d" />.

Why h:selectBooleanCheckbox not is updated? [duplicate]

Here is the scenario (simplified):
There is a bean (call it mrBean) with a member and the appropriate getters/setters:
private List<String> rootContext;
public void addContextItem() {
rootContext.add("");
}
The JSF code:
<h:form id="a_form">
<ui:repeat value="#{mrBean.stringList}" var="stringItem">
<h:inputText value="#{stringItem}" />
</ui:repeat>
<h:commandButton value="Add" action="#{mrBean.addContextItem}">
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
</h:form>
The problem is, when clicking the "Add" button, the values that were entered in the <h:inputText/> that represent the Strings in the stringList aren't executed.
Actually, the mrBean.stringList setter (setStringList(List<String> stringList)) is never called.
Any idea why?
Some info -
I'm using MyFaces JSF 2.0 on Tomcat 6.
The String class is immutable and doesn't have a setter for the value. The getter is basically the Object#toString() method.
You need to get/set the value directly on the List instead. You can do that by the list index which is available by <ui:repeat varStatus>.
<ui:repeat value="#{mrBean.stringList}" varStatus="loop">
<h:inputText value="#{mrBean.stringList[loop.index]}" />
</ui:repeat>
You don't need a setter for the stringList either. EL will get the item by List#get(index) and set the item by List#add(index,item).

Passing parameters as parameters in templates in JSF 2.0

I'm having difficulty finding support on this topic, because I know how to pass parameters to a template. What I want to do is pass parameters to not be used as parameters to the template but to a component within the template.
For example, in primefaces, you can write the following logic to create a button:
<p:commandButton action="#{printBean.print}">
<f:attribute name="report" value="report.jrxml" />
</p:commandButton>
This is all fine and good when I don't need to pass parameters. However, I need to construct a template which allows me to specify parameters to pass to the report dynamically. My first attempt was to do the following:
<p:commandButton actionListener="#{printBean.print}">
<f:attribute name="report" value="report.jrxml" />
<ui:insert name="reportParams" />
</p:commandButton>
Which would allow me to use the template in the following manner:
<ui:decorate template="templates/report.xhtml" >
<ui:define name="reportParams>
<f:attribute name="reportParam1" value="paramVal1" />
<f:attribute name="reportParam2" value="paramVal2" />
<f:attribute name="reportParam3" value="paramVal3" />
...
</ui:define>
</ui:decorate>
However parameters passed in this way are not received in my action listener in printBean, yet parameter "report" is. I think the attributes passed in this way are interpreted to mean that it is referring to the ui:define tag, and not to be inserted in the template as I would want.
Is there an alternative way of achieving the same way? Keep in mind I'm using JSF 2.0 and primefaces, but not Seam or any added libraries and ideally I would not have to add any libraries to make it work.
I apologize if an answer to this question already exists, but it's maddening searching for an answer to this question.
EDIT: The number of parameters is variable, meaning I can't simply use ui:param and put the value of that parameter as an attribute value within the template, because there could be many such parameters.
Use a composite component instead of a template.
Create this file /resources/mycomponents/printReport.xhtml:
<ui:component
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:cc="http://java.sun.com/jsf/composite"
xmlns:p="http://primefaces.org/ui"
>
<cc:interface>
<!-- No attributes. -->
</cc:interface>
<cc:implementation>
...
<p:commandButton value="Print" action="#{printBean.print}" />
...
</cc:implementation>
</ui:component>
Use it as follows:
xmlns:my="http://java.sun.com/jsf/composite/mycomponents"
...
<my:printReport>
<f:attribute name="reportParam1" value="paramVal1" />
<f:attribute name="reportParam2" value="paramVal2" />
<f:attribute name="reportParam3" value="paramVal3" />
</my:printReport>
Rewrite the print method as follows:
public void print() {
UIComponent composite = UIComponent.getCurrentCompositeComponent(FacesContext.getCurrentInstance());
String reportParam1 = (String) composite.getAttributes().get("reportParam1");
String reportParam2 = (String) composite.getAttributes().get("reportParam2");
String reportParam3 = (String) composite.getAttributes().get("reportParam3");
// ...
}

Email validation using regular expression in JSF 2 / PrimeFaces

I have an input field taking an email address:
<h:inputText value="#{register.user.email}" required="true" />
How can I validate the entered value as a valid email address using regex in JSF 2 / PrimeFaces?
All regular expression attempts to validate the email format based on Latin characters are broken. They do not support internationalized domain names which were available since May 2010. Yes, you read it right, non-Latin characters are since then allowed in domain names and thus also email addresses.
That are thus extremely a lot of possible characters to validate. Best is to just keep it simple. The following regex just validates the email format based on the occurrence of the # and . characters.
<f:validateRegex pattern="([^.#]+)(\.[^.#]+)*#([^.#]+\.)+([^.#]+)" />
Again, this just validates the general email format, not whether the email itself is legit. One can still enter aa#bb.cc as address and pass the validation. No one regex can cover that. If the validity of the email address is that important, combine it with an authentication system. Just send some kind of an activation email with a callback link to the email address in question and let the user login by email address.
Here is how:
Using it myself...
<h:inputText id="email" value="#{settingsBean.aFriendEmail}" required="true" label="Email" validatorMessage="#{settingsBean.aFriendEmail} is not valid">
<f:validateRegex pattern="[\w\.-]*[a-zA-Z0-9_]#[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]" />
</h:inputText>
<p:message for="email" />
Daniel.
Here's my version and it works well :
<f:validateRegex pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />
And i made a demo here
This one supports unicode domain names in email:
<f:validateRegex pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[\p{L}\p{M}\p{N}.-]*(\.[\p{L}\p{M}]{2,})$" />
... and this one validates email only when email is entered (email is not required field in form):
<f:validateRegex pattern="(^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[\p{L}\p{M}\p{N}.-]*(\.[\p{L}\p{M}]{2,})$)?" />
<p:inputText id="email" required="true" label="email" size="40"
requiredMessage="Please enter your email address."
validatorMessage="Invalid email format"
value="#{userBean.email}">
<f:validateRegex
pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />
</p:inputText>
<p:watermark for="email" value="Email Address *" />
<p:message for="email" />
<p:commandButton value="test" style="margin:20px"
action="#{userBean.register}" ajax="false" />

JSF 2.0 validateRegex with own validator message

i am having a code similar to this:
<h:inputText id="email" value="#{managePasswordBean.forgotPasswordEmail}"
validatorMessage="#{validate['constraints.email.notValidMessage']}"
requiredMessage="#{validate['constraints.email.emptyMessage']}"
validator="#{managePasswordBean.validateForgotPasswordEmail}"
required="true">
<f:validateRegex pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$" />
</h:inputText>
The validator in the backing bean has its own validation message generated. but it is overwritten by the validatorMessage of the inputText tag.
My Question is: how can i define a custom validator message for the validateRegex tag? I don't want to remove the validatorMessage cause then JSF is displaying an own error message containing the regex pattern and so on -> which i dont find very pretty.
Thanks for the help :)
You can't define a separate validatorMessage for each individual validator. Best what you can do is to do the regex validation in your custom validator as well, so that you can remove the validatorMessage.
Update: since version 1.3, the <o:validator> component of the JSF utility library OmniFaces allows you to set the validator message on a per-validator basis. Your particular case can then be solved as follows:
<h:inputText id="email" value="#{managePasswordBean.forgotPasswordEmail}"
required="true" requiredMessage="#{validate['constraints.email.emptyMessage']}">
<o:validator binding="#{managePasswordBean.validateForgotPasswordEmail}" message="#{validate['constraints.email.notValidMessage']}" />
<o:validator validatorId="javax.faces.RegularExpression" pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$" message="Your new custom message here" />
</h:inputText>
Unrelated to the concrete problem: these days you would be not ready for world domination as long as you still validate email addresses based on Latin characters. See also Email validation using regular expression in JSF 2 / PrimeFaces.
This worked for me.
You can write your custom messages in "validatorMessage"
<h:form id="form">
<h:outputLabel for="name">Name :</h:outputLabel>
<h:inputText id="name" value="#{editStock.name}" required="true" requiredMessage="Name field must not be empty" validatorMessage="Your name can have only Alphabets">
<f:validateRegex pattern="^[a-zA-Z]*$" />
</h:inputText><br/>
<h:message for="name" style="color:red" />
<h:commandButton value="Update" action="#{stock.update(editStock)}" style="width: 80px;"></h:commandButton>
</h:form>