Primefaces 3.5中的自定义验证器用于输入文本

时间:2014-06-04 10:17:16

标签: jsf jsf-2 primefaces

我的文本框的html / jsf代码是:

<p:inputText id="trainingNo" value="#{cpeTrainingMB.cpeTrainingObj.trainingNo}"
                                required="true" requiredMessage="Please Enter Training Number" binding="#{trainingNoComponent}">
                                <f:validator validatorId="trainingNoValidator"/>
                                <f:attribute name="trainingNoComponent" value="#{trainingNoComponent}"/>
                                </p:inputText>

我的验证员类是:

@FacesValidator("trainingNoValidator")
public class TrainingNoValidator implements Validator{

    @Override
     public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if (value == null) {
            return;
        }

        UIInput trainingNoComponent = (UIInput) component.getAttributes().get("trainingNoComponent");

        if (!trainingNoComponent.isValid()) {
            return;
        }

        Integer trainingNumber = (Integer) trainingNoComponent.getValue();
        System.err.println(trainingNumber);

        if (trainingNumber < 1) {
            return;
        }

        if (Integer.valueOf(DirectSqlUtils.
                getSingleValueFromTable("SELECT ISNULL((SELECT ISNULL(training_no, 0) FROM [dbo].[cpe_training] "
                        + "WHERE training_no = '"+trainingNumber+"'), 0)")
                .toString()) != 0) {
            System.err.println("Hello : "+DirectSqlUtils.
                getSingleValueFromTable("SELECT ISNULL((SELECT ISNULL(training_no, 0) FROM [dbo].[cpe_training] "
                        + "WHERE training_no = '"+trainingNumber+"'), 0)")
                .toString());
            trainingNoComponent.setValid(false);
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,"Training Number invalid.",null));

        }
    }

}

问题是当我将UI中的文本设置为1,2或3等时;事件中的对象总是返回0(零)而不是插入的文本。因此验证不能正常工作。我是JSF的新手。

1 个答案:

答案 0 :(得分:1)

您应该使用UIComponent#getSubmittedValue()getValue()假定组件已通过验证和转换。

getSubmittedValue意味着在完成验证之前使用

  

返回此UIInput组件的submittedValue值。此方法只应由此组件的decode()和validate()方法或其对应的Renderer使用。