JSF Number Validation - jsf

Is there any inbuilt number validator tag in JSF that checks whether an input entered in h:inputext field is a number?
The first question was answered. Edited to explain the next problem:
<h:inputText id="maxrecs" value="#{simpleBean.numRecords}" required="false" maxlength="4" >
<f:convertNumber longOnly="true"/>
</h:inputText>
Backing Bean
private long numRecords = null;
If I use String or Integer object in the backing bean , value is not being set. Now when I use primitive int, 0 is being printed on the screen. I would like the screen to be empty.

You can use f:convertNumber (use the integerOnly attribute).
You can get more information here.

You can use:
<f:validateLongRange minimum="20" maximum="1000" />
Where minimum is the smallest number allowed and maximum is the largest.
Look here for more details

JSF Number validation for inputtext
mention f:converterNumber component in between h inputText component and mention the attributes integerOnly and type.
<h:inputText id="textMobileId" label="Mobile" styleClass="controlfont" value="#{UserRegistrationBean.textMobile}">
<f:convertNumber integerOnly="true" type="number" />
</h:inputText>
If you enter abcd in Mobile textbox at the time when you click on commandbutton it automatically shows an error like
Mobile: 'abcd' is not a number.

i8taken solution converts number into long without validation message (at least in my case: JSF2 / global messages per page). For proper validation message you can
1. check value in action method in bean;
or
2. use converter attribute for inputText:
<h:inputText id="maxrecs" value="#{simpleBean.numRecords}" maxlength="4" converter="javax.faces.Integer" />

You can simply use the passthrough, so first add this library
xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
and after use this
<h:inputText id="numberId" pt:type="number" />

Related

How to hide validatorMessage when field is empty

Please help how to hide validatorMessage when user clearing the field:
<div class="item">
<p:outputLabel for="firstName" value="#{msgs['customerForm.firstName']}"/>
<p:inputText id="firstName" value="#{customerBean.customer.firstName}"
requiredMessage="#{msgs['Error.firstName.mandatory']}"
validatorMessage="#{msgs['Error.firstName.wrongFormat']}"required="true">
<f:validateRegex pattern="^([a-zA-Z]+[a-zA-Z\s\-]*){1,255}$" />
</p:inputText>
<p:message id="m_firstName" for="firstName" display="text"/>
</div>
You defined your field having two validations:
* required value validator
* regular expression validator
Both validators have equivalent priority, and both are run against your field value. And both of these validators see empty value as a problem, and your framework, unable to determine which of these two equivalent-looking failures is the "actual" failure, displays both.
To "fix" it, you should allow empty values to pass your regex, like this:
<f:validateRegex pattern="^([a-zA-Z]+[a-zA-Z\s\-]*){0,255}$" />
Notice that I changed number qualifier to allow 0-255 characters instead of 1-255 characters like before.
That should allow two of your validators cover different cases of invalid values, like you intended.
You can update the error messages if you put this in the input element. It will validate the input on every keyup event though.
<f:ajax execute="#this" event="keyup" render="m_firstName" />

Validation on checkbox and input field in jsf [duplicate]

I have a form which contains a dropdown and two input fields.
<h:selectOneMenu />
<h:inputText />
<h:inputText />
I would like to make the required attribute of the input fields conditional depending on the selected value of the dropdown. If the user chooses the first item of the dropdown, then the input fields must be required. If the user chooses the second item, then those would not be required.
How can I achieve this?
Just bind the dropdown to the view and directly check its value in the required attribute.
<h:selectOneMenu binding="#{menu}" value="#{bean.item}">
<f:selectItem itemValue="first" itemLabel="First item" />
<f:selectItem itemValue="second" itemLabel="Second item" />
</h:selectOneMenu>
<h:inputText value="#{bean.input1}" required="#{menu.value eq 'first'}" />
<h:inputText value="#{bean.input2}" required="#{menu.value eq 'first'}" />
Note that the binding example is as-is. Do absolutely not set it to a bean property here. See also How does the 'binding' attribute work in JSF? When and how should it be used?
Also note that the ordering of the components is significant. If the menu is located below the inputs in the tree, use #{menu.submittedValue eq 'first'} instead. Or if you want to be independent from that, use #{param[menu.clientId] eq 'first'} instead.
Assuming you are using JSF 2.0: Let your SelectOneListBox execute with ajax and re-render the input fields on change of the list box:
A quick sketch:
<h:selectOneMenu value="#{myBean.myMenuValue}">
<f:ajax render="input1"/>
..
</h:selectOneMenu>
<h:inputText id="input1" value="#{myBean.myInputValue}"
required="#{myBean.myMenuValue == 'firstEntry'}" />

How to Validate number field from <f:validateRegex>? [duplicate]

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>

JSF input processing order

Is there a way to specify the order in which the inputs should be set after a submit?
Here is my case:
<h:inputText id="fieldA" value=#{myBean.myObject.fieldA}" />
<h:inputText id="fieldB" value=#{myBean.myObject.fieldB}" />
<p:autoComplete id="myObject" value=#{myBean.myObject" converter="myObjectConverter" />
<h:inputText id="fieldC" value=#{myBean.myObject.fieldD}" />
<h:inputText id="fieldD" value=#{myBean.myObject.fieldC}" />
The issue I am encountering is that, as the inputs are processed in the ordered they are declared, fieldA and fieldB are set in the initial instance of myObject, then myObject is set (with a new instance thus filedA and fieldB values are lost), and finally fieldC and fieldD are set with no problem.
If I could manage to start by setting myObject first, that would solve my problem.
I will temporarily set the fields and myObject into two different attributes of my bean, and populate myObject after clicking a save button. But it looks more like a hack than a real solution.
Needless to say that declaring the autocomplete before the inputtexts is not an option.
Thanks in advance.
In shortcut:
You can use <p:inputText> tag from primefaces. Then, you can disable all inputs. Add ajax to your autoComplete, and update other inputs after processing autoComplete. Inputs disable attribute can be set to depend on whether the autoComplete is not null. This way you will make the user to enter the autoComplet first.
you can try to set immediate="true" to p:autocomplete, so that it will be processed in the APPLY_REQUEST_VALUES phase, before all other components.
The simple solution is to update h:inputTexts when p:autocomplete item is selected to reflect its values:
<p:autoComplete id="myObject" value="#{myBean.myObject}" ...>
<p:ajax event="itemSelect" process="#this" update="fieldA fieldB fieldC fieldD" />
</p:autoComplete>
but this reverts user inputs on h:inputTexts. And since you can't move p:autocomplete on top, probably this is not acceptable too.
In case you can't/don't want to use ajax, you can force an early model update:
<p:autoComplete id="myObject" value="#{myBean.myObject}" immediate="true"
valueChangeListener="#{component.updateModel(facesContext)}" ... />
but, in my opinion, this is not very user friendly...
P.S. this time it's tested :)
There's no pretty way to get around this; your situation is already less than ideal and is hacky (re: not being able to simply reorder the fields). One workaround is for you to set fieldA and fieldB as attributes of myObject. In the converter, you could then pull the values off the components. Observe
Set attributes thus
<h:inputText id="fieldA" binding=#{fieldA}" />
<h:inputText id="fieldB" binding=#{fieldB}" />
<p:autoComplete id="myObject" value=#{myBean.myObject" converter="myObjectConverter">
<f:attribute name="fieldA" value="#{fieldA}"/>
<f:attribute name="fieldB" value="#{fieldB}"/>
</p:autoComplete>
The binding attribute effectively turns those components into page-scoped variables, allowing you to then pass them as attributes on your p:autocomplete
Get the values of those variables in your converter
//Retrieve the fields and cast to UIInput, necessary
//to retrieve the submitted values
UIInput fieldA = (UIInput) component.getAttributes().get("fieldA");
UIInput fieldB = (UIInput) component.getAttributes().get("fieldB");
//Retrieve the submitted values and do whatever you need to do
String valueA = fieldA.getSubmittedValue().toString();
String valueB = fieldB.getSubmittedValue().toString();
More importantly, why can't you just reorder the fields/logical flow of your form? You can avoid all this nasty business if you did

required attribute of inputText should depend on submitted value of another component

I have a form which contains a dropdown and two input fields.
<h:selectOneMenu />
<h:inputText />
<h:inputText />
I would like to make the required attribute of the input fields conditional depending on the selected value of the dropdown. If the user chooses the first item of the dropdown, then the input fields must be required. If the user chooses the second item, then those would not be required.
How can I achieve this?
Just bind the dropdown to the view and directly check its value in the required attribute.
<h:selectOneMenu binding="#{menu}" value="#{bean.item}">
<f:selectItem itemValue="first" itemLabel="First item" />
<f:selectItem itemValue="second" itemLabel="Second item" />
</h:selectOneMenu>
<h:inputText value="#{bean.input1}" required="#{menu.value eq 'first'}" />
<h:inputText value="#{bean.input2}" required="#{menu.value eq 'first'}" />
Note that the binding example is as-is. Do absolutely not set it to a bean property here. See also How does the 'binding' attribute work in JSF? When and how should it be used?
Also note that the ordering of the components is significant. If the menu is located below the inputs in the tree, use #{menu.submittedValue eq 'first'} instead. Or if you want to be independent from that, use #{param[menu.clientId] eq 'first'} instead.
Assuming you are using JSF 2.0: Let your SelectOneListBox execute with ajax and re-render the input fields on change of the list box:
A quick sketch:
<h:selectOneMenu value="#{myBean.myMenuValue}">
<f:ajax render="input1"/>
..
</h:selectOneMenu>
<h:inputText id="input1" value="#{myBean.myInputValue}"
required="#{myBean.myMenuValue == 'firstEntry'}" />

Resources