【问题标题】:JSF validate on submit formJSF 验证提交表单
【发布时间】:2013-04-17 15:44:06
【问题描述】:

我正在处理一个 JSF 2.0 表单,我有一个带有 2 个字段的 managedbean

import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class StackOverflow {

    private Date firstDate;
    private Date secondDate;

    public void submit(){
       //validate here and show error on form
    }

}

和 xhtml 之类的:

<h:inputText value="#{stackOverflow.firstDate}">
    <f:convertDateTime pattern="d/M/yyyy" />
</h:inputText>
<h:inputText value="#{stackOverflow.secondDate}">
    <f:convertDateTime pattern="d/M/yyyy" />
</h:inputText>

<h:commandLink action="#{stackOverflow.submit}">
    <span>Submit</span>
</h:commandLink>

我想验证第二个日期不早于第一个日期的第一个和第二个日期

【问题讨论】:

标签: validation jsf-2


【解决方案1】:

这是其中一种方法:

<h:messages globalOnly="true"/>
<h:form>
    <h:inputText value="#{stackOverflow.firstDate}" binding="#{firstDate}">
        <f:convertDateTime pattern="d/M/yyyy" />
    </h:inputText>
    <h:inputText value="#{stackOverflow.secondDate}" validator="dateValidator">
        <f:attribute name="firstDate" value="#{firstDate}" />
        <f:convertDateTime pattern="d/M/yyyy" />
    </h:inputText>
    <h:commandButton value="Submit" action="#{stackOverflow.submit}"/>
</h:form>

@FacesValidator(value="dateValidator")
public class DateValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        UIInput sd = (UIInput)component.getAttributes().get("firstDate");
        Date firstDate = (Date)sd.getValue();
        Date secondDate = (Date)value;
        if(!firstDate.before(secondDate)){
            FacesMessage msg = new FacesMessage("Entered dates are invalid: first date must be before second date");
            throw new ValidatorException(msg);
        }
    }

}

【讨论】:

  • 你是如何得到 firstdate 的另一个值的??
  • 添加了第一个日期对应的&lt;h:inputText&gt; 作为另一个&lt;h:inputText&gt; 的属性,后来在validate 方法中访问它。真正值得一读的是JSF2.0 doesn't support cross-field validation, is there a workaround?
  • 这对我不起作用,除非使用直接值.. 绑定不起作用
  • “除了直接值”是什么意思?
  • 如果我输入 value="hello" 但不是 value=#{helloField} 则有效,这是因为我没有在目标字段中编写 binding="#{....}"
猜你喜欢
  • 2019-06-30
  • 2010-10-19
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多