Reputation: 9525
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>
Upvotes: 3
Views: 17824
Reputation: 18054
First, we need to distinguish between the events parse error and validation error.
parseError
is fired when the user input could not be parsed (e.g. "123123").validationError
is fired only when the input could be parsed but violates one of the constraints
defined in the property binding info object.With the help of type
and constraints
in property binding, invalid user inputs can be automatically prevented from being stored in the model.
Additionally, you can also register the control or the entire application in the MessageManager
for automatically generating the error messages in order to notify and guide the user what to do.
Refer to "Formatting, Parsing, and Validating Data" and "Validation Messages".
Here are some samples with sap.m.DateTimePicker
corresponding to the model:
JSONModel
globalThis.onUI5Init = () => sap.ui.require([
"sap/ui/core/mvc/XMLView",
"sap/ui/model/json/JSONModel",
"sap/ui/core/Core",
], async (XMLView, JSONModel, core) => {
"use strict";
const control = await XMLView.create({
definition: `<mvc:View xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
xmlns:core="sap.ui.core"
core:require="{
TypeDateTime: 'sap/ui/model/type/DateTime'
}"
displayBlock="true"
>
<App>
<Page showHeader="false" class="sapUiResponsiveContentPadding">
<ObjectAttribute title="Model value" text="{/myDate}" />
<ObjectAttribute title="Minimum Date" text="today" />
<DateTimePicker id="myDTP"
width="15rem"
value="{
path:'/myDate',
type: 'TypeDateTime',
formatOptions: {
style: 'medium/short'
}
}"
parseError="alert('Parse error')"
validationError="alert('Validation error')"
/>
</Page>
</App>
</mvc:View>`,
afterInit: function() {
const dateTimeValueBinding = this.byId("myDTP").getBinding("value");
dateTimeValueBinding.getType().setConstraints({
minimum: new Date(), // today
});
},
models: new JSONModel({
myDate: new Date(),
}),
});
core.getMessageManager().registerObject(control, true);
control.placeAt("content");
});
<script id="sap-ui-bootstrap"
src="https://sdk.openui5.org/resources/sap-ui-core.js"
data-sap-ui-libs="sap.ui.core,sap.m,sap.ui.unified,sap.ui.layout"
data-sap-ui-theme="sap_horizon_dark"
data-sap-ui-async="true"
data-sap-ui-oninit="onUI5Init"
data-sap-ui-compatversion="edge"
data-sap-ui-excludejquerycompat="true"
data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>
sap/ui/model/type/DateTime
ODataModel
globalThis.onUI5Init = () => sap.ui.require([
"sap/ui/core/mvc/XMLView",
"sap/ui/model/odata/v4/ODataModel",
"sap/ui/core/mvc/Controller",
"sap/ui/core/Core",
], async (XMLView, ODataModel, Controller, core) => {
"use strict";
const control = await XMLView.create({
definition: `<mvc:View controllerName="demo.MyController"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
xmlns:core="sap.ui.core"
core:require="{
TypeDateTimeOffset: 'sap/ui/model/odata/type/DateTimeOffset'
}"
displayBlock="true"
>
<App>
<Page
showHeader="false"
class="sapUiResponsiveContentPadding"
binding="{
path: '/People(userName=%27sandyosborn%27)/Trips(20)',
events: {
dataReceived: '.onDateTimeReceived'
}
}"
>
<ObjectAttribute
title="Model value"
text=""{ path: 'StartsAt', targetType: 'any' }""
/>
<ObjectAttribute title="Nullable" text="false" />
<DateTimePicker id="myDTP"
busy="true"
busyIndicatorDelay="1"
width="15rem"
value="{
path: 'StartsAt',
type: 'TypeDateTimeOffset',
formatOptions: {
style: 'medium/short'
},
constraints: {
nullable: false
}
}"
parseError="alert('Parse error')"
validationError="alert('Validation error')"
/>
</Page>
</App>
</mvc:View>`,
models: new ODataModel({
serviceUrl: "https://services.odata.org/TripPinRESTierService/(S(o1bizjomxywpc12mu2ad3fje))/",
autoExpandSelect: true,
operationMode: "Server",
}),
controller: new (Controller.extend("demo.MyController", {
onDateTimeReceived: function() {
this.byId("myDTP").setBusy(false);
},
}))(),
});
core.getMessageManager().registerObject(control, true);
control.placeAt("content");
});
<script id="sap-ui-bootstrap"
src="https://sdk.openui5.org/resources/sap-ui-core.js"
data-sap-ui-libs="sap.ui.core,sap.m,sap.ui.unified,sap.ui.layout"
data-sap-ui-theme="sap_horizon_dark"
data-sap-ui-async="true"
data-sap-ui-oninit="onUI5Init"
data-sap-ui-compatversion="edge"
data-sap-ui-excludejquerycompat="true"
data-sap-ui-resourceroots='{ "demo": "./" }'
data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>
sap/ui/model/odata/type/DateTimeOffset
Unlike sap/ui/model/type/Date*
, there is currently no support for minimum
& maximum
constraints in sap/ui/model/odata/type/*
yet (Except for Decimal
).
Until then, you could extend the DateTimeOffset
type and implement the validateValue
method accordingly. Sample: https://embed.plnkr.co/qatUyq
Upvotes: 3
Reputation: 361
If you don't want to that much work in JS, I believe you can work with the validationError
event. Simply set in in your XML, validationError="functionNameHere"
and in your JS you can just set the ValueState to error. The validationError
event is fired when the value can't be sent to the model, so you don't have to do any checks on the formatting, this event occurring means the formatting is indeed wrong. You can check the link below to read the documentation.
Upvotes: 0
Reputation: 4231
You have to use the fully qualified object name in your data type declaration as you're referring to a JavaScript object not to a build in HTML type. If you change the following part:
DateTime
to sap.ui.model.type.DateTime
it will work. Please be aware that attributes like valueFormat
or displayFormat
as used in your example are ignored if a type is in use. In this case you have to provide these information in the binding. For further details please check the documentation of the type implementation.
An shortened example can be found here. More examples can be found in the UI5 Explored application which is in general a good starting point. An explanation of binding in general can be found here.
Upvotes: 1
Reputation: 1754
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.
Upvotes: 5