sapui5date-range

How can I prevent dates being selected which are prior to that in another input?


In a form, I have two DatePicker fields which are From and To. In this case user should not be able to choose a value for To less than what he/she choose for the From field.

I just wanted to know is there any SAPUI5 native way to do this comparison and validate the DatePicker fields? In the image blow, you can see that the From has a greater value than the To, which is wrong! In this case, I need to show the validation error around the fields.

enter image description here


Solution

  • Assume you have the following 2 DatePicker objects in your xml view file:

    <m:DatePicker id="__input_validFrom" 
       value="{path: 'ZValidFrom', type : 'sap.ui.model.type.Date'}"
       fieldGroupIds="fieldGroup1" 
       change="handleValidFromChange"/>
    
    <m:DatePicker id="__input_validTo" 
       value="{path: 'ZValidTo', type : 'sap.ui.model.type.Date'}" 
       fieldGroupIds="fieldGroup1" 
       change="handleValidToChange" />
    

    These 2 fields show the date in a suitable format as we set the type to sap.ui.model.type.Date.

    Now we have to play with constraints of the sap.ui.model.type.Date in the onChange event handler:

    handleValidFromChange: function (oEvent) {
        var oDatePicker = oEvent.getSource(),
            sValue = oDatePicker.getValue(),
            sToDatePicker = "__input_validTo",          
            oToDatePicker = this.byId(sToDatePicker);
        oToDatePicker.getBinding("value").setType(new sap.ui.model.type.Date(null, {
            minimum: new Date(sValue)
        }), "string");
    },
    handleValidToChange: function (oEvent) {
        var oDatePicker = oEvent.getSource(),
            sValue = oDatePicker.getValue(),
            sFromDatePicker = "__input_validFrom",
            oFromDatePicker = this.byId(sFromDatePicker);
        oFromDatePicker.getBinding("value").setType(new sap.ui.model.type.Date(null, {
            maximum: new Date(sValue)
        }), "string");
    }
    

    As soon as user change value in one of fields we change the constraints in the other field.

    Notes:

    1. Please note that we cannot directly bind the constraints to a model.
    2. By applying this solution you need to use validation on date pickers to see some validation state text.