【问题标题】:JSF: How to validate an inputText only when another component is selectedJSF:如何仅在选择另一个组件时验证 inputText
【发布时间】:2012-08-15 22:50:42
【问题描述】:

我有三个单选按钮,一个 inputText 和一个提交按钮。我只想在选择某个收音机时验证提交时的输入文本。所以我有

<h:inputText validator="#{myBean.validateNumber}" ... />

我的豆子里有

 public void validateNumber(FacesContext context, UIComponent component,
                Object value) throws ValidatorException{
      if(selectedRadio.equals("Some Value"){
           validate(selectedText);
      }
 }

 public void validate(String number){
      if (number != null && !number.isEmpty()) {
        try {
            Integer.parseInt(number);
        } catch (NumberFormatException ex) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Error", "Not a number."));
        }
      } else {
        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Error", "Value is required."));
      }
 }

使这不起作用的一件事是,当我提交时,validateNumber(...) 在我的单选按钮 setSelectedRadio(String selectedRadio) 的设置方法之前运行。因此造成这种说法

 if(selectedRadio.equals("Some Value"){
       validate(selectedText);
 }

无法正确执行。关于如何解决这个问题的任何想法?

【问题讨论】:

    标签: jsf jsf-2


    【解决方案1】:

    selectedRadio 是一个模型值,仅在更新模型值阶段更新,该阶段验证阶段之后。这就是为什么在您尝试检查它时它仍然是初始模型值。

    您必须从请求参数映射(这是原始提交的值)或 UIInput 引用中获取它,以便您可以通过 getSubmittedValue() 获取提交的值或转换/验证getValue() 的值。

    所以,

    String selectedRadio = externalContext.getRequestParameterMap().get("formId:radioId");
    

    UIInput radio = (UIInput) viewRoot.findComponent("formId:radioId"); // Could if necessary be passed as component attribute.
    String submittedValue = radio.getSubmittedValue(); // Only if radio component is positioned after input text, otherwise it's null if successfully converted/validated.
    // or
    String convertedAndValidatedValue = radio.getValue(); // Only if radio component is positioned before input text, otherwise it's the initial model value.
    

    【讨论】:

    • 谢谢你,BalusC。有用。你的omnifaces验证器能解决这个问题吗?我在考虑 o:validateOrder,但我觉得它可能不起作用,因为我需要先验证是否选择了收音机
    • 在 OmniFaces 中没有这样的东西。这也是一个相当具体的要求。我个人宁愿使用&lt;f:validateXxx disabled="#{param['formId:radioId'] != 'some value'}" /&gt; 或其他东西。请注意,还有一个&lt;f:validateRequired&gt; 可以用这种方式替换required="true"
    • 嗨 BalusC。只是出于好奇,验证阶段将提供什么。我觉得在这个阶段什么都没有,因为验证是在更新模型值阶段之前。例如,如果我只有一个常规 inputText,并且我想验证用户在其中输入的值,那么在更新模型阶段之前,该值不会设置为我的绑定变量。我仍然必须通过请求参数映射来获取它,不是吗。对我来说似乎有点傻。
    • 需要验证的组件自己的值仅作为validate()方法的第三个参数可用。
    • 天哪,我知道。真是愚蠢。谢谢你的叫醒。
    【解决方案2】:

    它被称为跨字段验证(验证不仅基于一个组件的值,而是一组它们)。

    目前,JSF2 不支持它(JSF doesn't support cross-field validation, is there a workaround?)但是有几个库(在提到的问题omnifaces 中提到,看起来seamfaces 也有它的东西)可能会有所帮助。在问题中还有一种解决方法。

    【讨论】:

      猜你喜欢
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多