JSF 2.0 validateRegex with own validator message - regex

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>

Related

Encoding of spaces in POJO parameters in Axis2

I have created a very simple service that just echos some text to the console. The service is just a POJO with a method echo, having a single parameter:
public class EchoTest
{
public void echo(String myMessage)
{
System.out.println(myMessage);
}
}
Ths is from the services.xml:
<service name="EchoTest">
<description>Echo test</description>
<parameter name="ServiceClass">EchoTest</parameter>
<operation name="echo">
<messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
</operation>
</service>
Further I use a very simple HTML form to submit the data to the service:
<html>
<body>
<form method="post" target="responseFrame" action="../../services/EchoTest/echo">
<input name="myMessage" type="text">
<input value="Send" type="submit"/>
</form>
<iframe width=500 height=500 name="responseFrame"></iframe>
</body>
</html>
The problem I have is that spaces are replaced with '+'. For example, if I type a message like this:
Hey you & you - # % #
The result is this:
Hey+you+&+you+-+#+%+#
Do I have to encode it somehow or or should it not behave like this? Or perhaps it is a setup issue? I am using Tomcat as a web container. For information, I use a servlet filter in Tomcat to e.g. filter on IP addresses, and in there I can see that the myMessage parameter looks OK, not having + signs.
It turns out that the problem was in fact within Axis2 itself. I am not sure exactly, but the version that I was using was release 1.5.1 from October 2009. What bugs me is that I have not found any bug report on it. It could be that it was fixed quickly and that I was unfortunate.
Upgrading to a the latest version of Axis2 solved the problem.

CFWheels - DeObfuscate ID on query paging?

I am obfuscating URL's in my app (which is great), but I'd like to disable this for pagination URL's because I'd like the user to be able to enter whatever number they like.
Settings.cfm:
<cfset set(obfuscateURLs = true) />
Home.cfc (controller):
<cffunction name="home">
<cfparam name="params.page" default="1" />
<cfset linkList = model("link").findAll(
select="linkTitle,linkPoints,linkID,linkAuthority,linkCreated,linkUpVoteCount,linkDownVoteCount,linkCommentCount,userName,userID",
include="user",
order="linkPoints DESC",
handle="linkListPaging",
page=params.page,
perPage=5
) />
</cffunction>
Home.cfm (view)
<ul class="pagination">
<cfoutput>
#paginationLinks(
route="paginateLatest",
handle="linkListPaging",
page=1,
name="page",
windowSize=5,
prependToPage="<li>",
appendToPage="</li>",
classForCurrent="current"
)#
</cfoutput>
</ul>
Can I do DeObfuscate on an as needed basis?
Thanks,
Michael
The setting to obfuscate params is an all-or-nothing deal. Just as you can't override this behavior for linkTo(), you cannot override it for paginationLinks() either.
I would suggest building a plugin as I bet there will be other developers out there who would want this in the future. There may be a way to tell the controller to not obfuscate/deobfuscate a parameter named page. You would need to update both how urlFor() works as well as how the controller deobfuscates as it handles incoming requests. You may also consider providing a configuration option to use set() to "blacklist" a set of params keys to never be obfuscated (with page being a default).

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?
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>

List contains method not working in JSF page

I have two list that consist out of the same object.
I want to check if the first list containts an object of the second list
<ui:repeat var="item" value="#{userTypeController.permissionItems}">
<c:if test="#{userTypeController.permissionItemsUserType.contains(item)}">
<h:selectBooleanCheckbox value="#{true}"/>
<h:outputText value="#{item.getAction()}" />
</c:if>
<c:if test="#{!userTypeController.permissionItemsUserType.contains(item)}">
<h:selectBooleanCheckbox value="#{false}"/>
<h:outputText value="#{item.getAction()}" />
</c:if>
</ui:repeat>
but this doesn't seem to work and all I'm getting is false.
I've changed the equals and hashcode methodes but didn't help.
JSTL tags like <c:if> runs during view build time and the result is JSF components only. JSF components runs during view render time and the result is HTML only. They do not run in sync. JSTL tags runs from top to bottom first and then JSF components runs from top to bottom.
In your case, when JSTL tags runs, there's no means of #{item} anywhere, because it's been definied by a JSF component, so it'll for JSTL always be evaluated as if it is null. You need to use JSF components instead. In your particular case a <h:panelGroup rendered> should do it:
<ui:repeat var="item" value="#{userTypeController.permissionItems}">
<h:panelGroup rendered="#{userTypeController.permissionItemsUserType.contains(item)}">
<h:selectBooleanCheckbox value="#{true}"/>
<h:outputText value="#{item.getAction()}" />
</h:panelGroup>
<h:panelGroup rendered="#{!userTypeController.permissionItemsUserType.contains(item)}">
<h:selectBooleanCheckbox value="#{false}"/>
<h:outputText value="#{item.getAction()}" />
</h:panelGroup>
</ui:repeat>
See also:
JSTL in JSF2 Facelets... makes sense?

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" />