Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex with p:keyFilter

I have an p:inputMask with a p:keyFilter to match time in the HH:mm pattern as following:

<p:inputMask mask="99:99" ...>
     <p:keyFilter regEx="([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]"/>
</p:inputMask>

But it doesn't work and it accepts all values from 00:00 to 99:99.

How can I solve this?

like image 301
Renaud is Not Bill Gates Avatar asked Aug 02 '26 06:08

Renaud is Not Bill Gates


1 Answers

p:keyFilter versus f:validateRegexregEx versus inputRegEx

p:keyFilter with the regEx attribute is used to filter characters (on each key stroke), it does not allow you to validate an expression (on the complete inputted value). If you want to validate if your input matches a regular expression, use the inputRegEx attribute or f:validateRegex.

So, in your case you could use:

<p:inputXxx ...>
    <f:validateRegex pattern="([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]"/>
</p:inputXxx>

Please note that p:keyFilter requires JavaScript regular expressions, while, while f:validateRegex requires a Java regular expression. And, p:keyFilter inputRegEx is checked on key up, while f:validateRegex is executed when the field is processed. The proper way to use p:keyFilter would be:

<p:inputXxx ...>
    <p:keyFilter inputRegEx="/[0-9:]/"/>
</p:inputXxx>

But that will still allow invalid input.

So, in resume:

Property p:keyFilter inputRegEx="..." f:validateRegex pattern="..."
Regular expression type JavaScript Java
Executed when Key up JavaScript event is triggered Component is processed

This applies to all text input components (like p:inputText), so not only to the p:inputMask you are using).

See also:

  • https://primefaces.github.io/primefaces/10_0_0/#/components/keyfilter
  • Convert Javascript regular expression to Java syntax

Before PrimeFaces 6

Note that p:keyFilter is available since 6.0. For older versions you need PrimeFaces Extensions pe:keyFilter. Note that versions of PFE before 6.0 do not align with PF versions.

For something completely different

You could simply use p:datePicker, which nowadays can be used to enter time (hours and minutes) only:

<p:datePicker pattern="HH:mm" .../>

Or you could have a look at pe:timePicker.

like image 54
Jasper de Vries Avatar answered Aug 06 '26 11:08

Jasper de Vries



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!