Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

validation - JSF validate on submit form

I'm working on a JSF 2.0 form, I have a managedbean with 2 fields

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
    }

}

and the xhtml like:

<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>

I want to validate the first and second date that the second date is not before the first date

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's one of the ways:

<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>

with

@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);
        }
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...