2

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

0

3 Answers 3

2

Is there any SAPUI5 native way to do this

Yes, take a look at the Date Range Selection.

Sample

globalThis.onUI5Init = () => sap.ui.require([
  "sap/ui/core/Fragment",
  "sap/ui/model/odata/v4/ODataModel",
  "sap/ui/core/message/MessageManager",
], async (Fragment, ODataModel, messageManager) => {
  "use strict";
  const definition = document.getElementById("myxmlfragment").textContent;
  const control = await Fragment.load({ definition });
  control.setModel(new ODataModel({
    serviceUrl: "https://services.odata.org/TripPinRESTierService/(S(myservice))/",
  })).placeAt("content");
  messageManager.registerObject(control, true);
});
<script defer id="sap-ui-bootstrap"
  src="https://sdk.openui5.org/nightly/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core,sap.m,sap.ui.layout,sap.ui.unified"
  data-sap-ui-oninit="onUI5Init"
  data-sap-ui-theme="sap_horizon_dark"
  data-sap-ui-async="true"
  data-sap-ui-compatversion="edge"
  data-sap-ui-excludejquerycompat="true"
  data-sap-ui-xx-waitfortheme="init"
></script>
<script id="myxmlfragment" type="text/xml">
  <VBox xmlns="sap.m" xmlns:core="sap.ui.core"
    core:require="{
      ODataV4DateTimeOffset: 'sap/ui/model/odata/type/DateTimeOffset',
      DateInterval: 'sap/ui/model/type/DateInterval'
    }"
    renderType="Bare"
    binding="{/People('russellwhyte')/Trips(0)}"
  >
    <Text text="{ path: 'StartsAt', targetType: 'any' }" />
    <Text text="{ path: 'EndsAt', targetType: 'any' }" />
    <DateRangeSelection
      placeholder="&lt;From> - &lt;To>"
      width="16rem"
      value="{
        parts: [
          {
            path: 'StartsAt',
            formatOptions: { UTC: true },
            type: 'ODataV4DateTimeOffset'
          },
          {
            path: 'EndsAt',
            formatOptions: { UTC: true },
            type: 'ODataV4DateTimeOffset'
          }
        ],
        type: 'DateInterval',
        formatOptions: { UTC: true },
        parameters: {
          $$noPatch: true
        }
      }"
    />
  </VBox>
</script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>

Note: the above sample makes use of sap.ui.model.odata.v4.ODataModel. The same approach can be applied to the V2 model which, however, requires explicitly enabling two-way binding with e.g. defaultBindingMode: "TwoWay" in the model settings. Additionally, binding definitions also differ in V2. Please review the documentation topic "Dates, Times, Timestamps, and Time Zones" and adjust the data settings accordingly. The above sample makes use of the entity properties with Type="Edm.DateTimeOffset" which is not really suitable for the DateRangeSelection control. The property type should be rather "Edm.Date" in OData V4 or "Edm.DateTime" with sap:display-format="Date" in V2.

Result

sap.m.DateRangeSelection

This resolves the given problems:

  • User needs to pick two date values. ✔️
  • User should not be able to choose To less than From. ✔️
  • Looking for "UI5 native way" to solve this. ✔️

Use it in combination with the binding type: sap.ui.model.type.Date*Interval to enable:

  • Two-way data binding ✔️
  • Format options ✔️
  • Input validation with standard UI messages ✔️

Compared to the custom implementation in JavaScript with two DatePickers, the DateRangeSelection control allows:

  • Less clicks for the user ✔️
  • Zero custom JS code to handle date ranges ✔️

See the documentation topic "Dates, Times, Timestamps, and Time Zones" (must-read IMO).

1

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

By using the change event on the "from" picker we can then use the method setMinDate() for the "To" picker based on the date picked so the user can only select dates after the date selected.

On our XML view we can have both sap.m.DatePicker:

<DatePicker id="DP1" placeholder="Enter Date ..." change="handleChange"/>
<DatePicker id="DP2" placeholder="Enter Date ..."/>

And in our controller we can then apply the logic:

handleChange: function(oControlEvent) {
   //get date picked from first picker
   var sDatePicked = oControlEvent.getSource().getDateValue();
   //set minimum date on second picker
   this.getView().byId("DP2").setMinDate(sDatePicked).setValue();
}

By applying this method we can now get the new value from the first sap.m.DatePicker and apply it to the "To" Date Picker by using the setMinDate() method and reset its value so the user has to select a new date.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.