I want to compare two dates (StartDate and EndDate) and check whether one is before the other. The simplest solution is to just do it on the backing bean and "short-circuit" the method.
However this validation does not happen concurrently with the other form validations. For example if I have another field that requires validation (besides the dates) and has invalid input, I will only get a message for that specific field. Only if the other fields are valid will I get the date validation based on the backing bean.
Anyone have a solution?
As BalusC solution works only if you have one date range to validate on the form, here is an improvement to allow multiple date range validations:
add another
<f:attribute>
to the endDate calendar component where you specify the binding attribute name to startDate component:then in the validator:
if you're using PrimeFaces which can limit a minimum and maximum dates. the user could not choose a greater range this is an example:
Taking the Answer BalusC like Base, and for me use in the future...
This can to set the Interval (Year, Month, Week), the Reference Comparation Initial, or Final.
}
Now in the view
A backing bean action method is indeed not intented to perform input validation.
Use the right tool for the job; use a normal
Validator
.Validating multiple input values with a single validator is in turn however indeed a story apart. Basically, you should be grabbing/passing the other component or its value along into the
validate()
method implementation. In its simplest form, you could use<f:attribute>
for this. Assuming that you're using<p:calendar>
to pick dates, here's a concrete kickoff example:(note the
binding
attribute, it makes the component available in the EL scope on exactly the given variable name; also note that this example is as-is and that you should absolutely not bind it to a bean property!)Where the
dateRangeValidator
look like this:If you happen to use JSF utility library OmniFaces, then you could also just use its
<o:validateOrder>
component. The requirement can be achieved as follows without the need for a custom validator:See also: