Search code examples
sapui5

Validate input of datetime picker


How to register validationError callback for datetimepicker in XML view and how to get this event fired for invalid date input.

The datetimepicker control is an input box with a popup date picker.

The user can type directly into the input or use the date picked to select a date. I can add sophisticated validation to the datetime value but I am trying to simply trigger the validationError event when the user types an invalid date into the box, for example "1010101010010101010101010" or "32/15/2019".

Ideally I am looking for a constraint that tests for a valid date value and triggers the validationError() function if needed.

I guess a workaround is to use the change() event and do the validation in JS, set the valueState etc, but I want to understand what the datetimepicker can do in this regard without having to resort to excess JS.

I am convinced this must be in the docs somewhere but have not yet found anything conclusive. I feel strictParsing should play some part.

I found this SO questionabout setting date range constraints via declaring a new data type. I thought this might be a solution but I am stuck with how to set the constraint for 'a valid date' input value.

Reading the SAPUI5 docs about sap.ui.model.type.DateTime it mentions

The DateTime type supports the following validation constraints:

maximum (expects an dateTime presented in the source-pattern format) minimum (expects an dateTime presented in the source-pattern format)

which gives no pointers over how to do a straight date validity or format check.

Can anyone point me in the right direction?

EDIT - on suggestion of @Matbtt and reference to docs I altered the type to the string literal sap.ui.model.type.DateTime. However the snippet then produced no output. I traced this to the binding to the model where I was binding to a string. When changed to bind to a JS date object this was fixed.

EDIT - on suggestion of @Developer added validationError callback but does not appear to work. See snippet.

// JSON sample data
var classData = {className: "Coding 101", id: 800, startdate: "2017-12-31T23:59:59.000"}

// convert JSON date to JS date object and format via moment for UI5 consumption
classData.startdateraw = new Date(classData.startdate)
classData.startdatefmt = moment(classData.startdateraw).format('YYYY-MM-DD-HH-mm-ss') 

sap.ui.getCore().attachInit(function() {
   "use strict";
   sap.ui.controller("MyController", {
     onInit: function() {

    // create JSON model instance
    var oModel = new sap.ui.model.json.JSONModel();

    // set the data for the model
    oModel.setData(classData);
   
    // set model to core.
    sap.ui.getCore().setModel(oModel);

    // Enable validation !!
    sap.ui.getCore().getMessageManager().registerObject(this.getView(), true);
     
    
     this.getView().byId("startDate").attachValidationError(function(){
        
        alert('Validation error fires - hoorah')
        
      }) 
       
     },
     valError : function(){
       console.log("There was a validation error")
      }
   });
   sap.ui.xmlview({
     viewContent: jQuery("#myView").html()
   }).placeAt("content");
  
  });
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/1.7.2/moment.min.js"></script>
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m" data-sap-ui-bindingSyntax="complex" data-sap-ui-compatVersion="edge" data-sap-ui-preload="async"></script>

<script id="myView" type="ui5/xmlview">
  <mvc:View controllerName="MyController" xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns:layout="sap.ui.commons.layout" xmlns:f="sap.ui.layout.form">


    <f:SimpleForm id="EditForm" maxContainerCols="2" editable="true" width="25rem" layout="ResponsiveGridLayout" path="{}">
      <f:content>


        <Label id="lblStartDate" text="Start" design="Bold" labelFor="startDate" />
        <DateTimePicker 
            id="startDate" 
            placeholder="Enter a crazy date and time, e.g. 23/01/12345" 
            valueFormat="yyyy-MM-dd-HH-mm-ss" 
            validationError="valError"
            value="{
            	path: '/startdateraw',
                type: 'sap.ui.model.type.DateTime',  
                strictParsing: 'true'
              }" 
              />


      </f:content>
    </f:SimpleForm>

  </mvc:View>
</script>

<div id="content"></div>


Solution

  • You can do it by handling change event of sap.m.DateTimePicker:

    handleChange : function(oEvent){
       var bValid   = oEvent.getParameter("valid");
    
       if(!bValid){             
          sap.m.MessageToast.show("Entered date range isn't valid");
          return;
       }
    }
    

    Jsbin working example.

    EDITED 15:03 310117

    Change event of sap.m.DateTimePicker is borrowed event from class sap.m.DatePicker.