1
votes

Silly question, but that's my situation. I am having editable PrimeFaces selectOneMenu where inputField has following restriction:

  • lower and upper limit of number typed in
  • predefined text allowed
  • when decimal number is being typed allow only 2 decimal numbers

All is good except the last one with decimal number restriction. What it means is that I can't type there 1.111 but only 1.11. Change event keyUp for selectOneMenu is sadly added to the tag select but not to input.

Any ideas how to solve?

1

1 Answers

2
votes

This calls for a custom validator. Create one which checks for the predefined values, if no match is found, check the number format. Basic example:

@FacesValidator("myValidator")
public class MyValidator implements Validator
{

  private List<String> predefinedValues = Arrays.asList("my", "list");

  @Override
  public void validate(FacesContext context, UIComponent component, Object value)
  throws ValidatorException
  {
    String valueStr = (String) value;
    // Check if value is predefined
    if (predefinedValues.contains(valueStr)) {
      return;
    }
    // If not predefined, check number format
    if (! valueStr.matches("^\\d+(\\.\\d\\d?)?$")) {
      throw new ValidatorException(new FacesMessage("Value is invalid!"));
    }
    // Check number limits...
  }

}

The validator can be used in your XHTML as:

<p:selectOneMenu editable="true" ...>
  ...
  <f:validator validatorId="myValidator" />
</p:selectOneMenu>

As an alternative you could use jQuery to find the input field and bind a keypress listener to it. See for example: Jquery: filter input on keypress. However, I would keep the validator in place. Users could paste text for example.

See also: