Search code examples
javascriptvalidationdatesapui5

SAPUI5 Localized Date Validation


Does anybody know which date formats SAPUI5 is using to validate localized dates with sap.m.DatePicker?

Example: When using sap.m.DatePicker with displayFormat "MMMM d, y" in en-US, I type "12/31/18" and it gets converted to "December 31, 2018", but when I type "12/31/2018" it doesn't seem to be a valid input.


Solution

  • I figured it out! If there is no valueFormat provided for the sap.m.DatePicker, the input validation is based on the displayFormat and a couple of fallback formats which are specific to the given locale. In en_US the fallback formats are:

    MMddyyyy
    MMddyy
    M/d/yy
    MMM d, y
    yyyy-MM-dd
    yyyyMMdd
    MMddyyyy
    MMddyy

    "12/31/2018" doesn't match any of those formats and therefore is not considered valid. I created this tool so you can check the locale specific formats and test some standard or custom display formats: http://jsbin.com/xalinujafi/edit?output

    Getting the DatePicker looks like this:

    var oDateFormat = sap.ui.core.format.DateFormat.getDateInstance({style: 'long'});
    var oDate = new sap.m.DatePicker({
        width: '19.25rem',
        displayFormat: oDateFormat.oFormatOptions.pattern,
        change: function(oEvent){
            var oSource = oEvent.getSource();
            var oFormat = oSource._oDisplayFormat;
            if (!oFormat.parse(oSource.getValue())) {
                oSource.setValueState("Error");
                oSource.setValueStateText("Invalid Input");
            } else {
                oSource.setValueState("None");
                oSource.setValueStateText("");
            }
        }
    });