Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
ManabuInoue
Discoverer
356

Introduction

In May 2021, when I implemented a registration screen in my SAPUI5 freestyle application, I had trouble implementing input value validation. Although the standard provided validation mechanism has validations that are executed on value changes such as change events, what I wanted to achieve was the following.

  • Execution of batch validation of input items when the save button is pressed
  • Required input check
  • Correlation checks between multiple items (e.g. checking for pre- and post-relationships between start and end dates)

I started writing a validation library for UI5 applications to achieve these goals. v0.1.0 was released on npm in May 2021, and after a number of feature additions, bug fixes, and TypeScript migration, v1.0.0 was recently released after about a year of production use.

npm: https://www.npmjs.com/package/@learnin/ui5-validator
GitHub: https://github.com/learnin/ui5-validator

Characteristics

  • This uses the UI5 standard required attribute and message management mechanism and coexists with standard validation by constraints attribute, so there is no need to add your own attributes or controls to the control to be validated.
  • This provides a mechanism to manage required input validation and any validation logic, and you are free to implement and use your own validation logic.

Features

  • Required validation with the UI5 standard required attribute.
  • Can be run in conjunction with standard UI5 constraints.
  • Implement and use any validation logic, including single-item validation and multiple-item correlation validation etc.
  • Any validation logic can be executed on focus-out, similar to the UI5 standard constraints.
  • Validations can be performed on the whole view or on a per-control basis.
  • Controls in sap.ui.table.Table and sap.m.Table can also be validated.

Demo

Please give it a try. https://learnin.github.io/ui5-validator/demo/

スクリーンショット 2025-01-30 22.35.16.png

 Setup

npm install @learnin/ui5-validator

Create webapp/libs directory and copy files under node_modules/@learnin/ui5-validator/dist/resources/ into libs.

Add sap.ui5.dependencies.libs.learnin.ui5.validator and sap.ui5.resourceRoots.learnin.ui5.validator to manifest.json as follows.
Also, set sap.ui5.handleValidation to true to enable UI5 standard validation.

{
    // ...
    "sap.ui5": {
        // ...,
        "handleValidation": true,
        "dependencies": {
            // ...,
            "libs": {
                // ...,
                "learnin.ui5.validator": {}
            }
        },
        "resourceRoots": {
            "learnin.ui5.validator": "./libs/learnin/ui5/validator/"
        },
        // ...

Basic Usage

View:

 

<mvc:View
    ...
    xmlns="sap.m">
    ...
    <Label text="{i18n>label.xxx}" />
    <Input
        value="{
            path: '{xxx>/xxx}',
            type: 'sap.ui.model.type.String',
            constraints: {
                maxLength: 10
            }
        }"
        maxLength="10"
        required="true" />

 

Controller:

Easy to copy https://github.com/learnin/ui5-validator/blob/main/example/webapp/controller/BaseController.js and extend.

 

sap.ui.define([
    "./BaseController",
    "learnin/ui5/validator/Validator"
], function (BaseController, Validator) {
    "use strict";

    return BaseController.extend("learnin.ui5.validator.example.controller.ValidatorExample", {
        onInit: function () {
            this._validator = new Validator();
        },

        onExit: function () {
            // Remove functions that are automatically attached to an argument and its subordinate controls by a validator.
            this._validator.removeAttachedValidators(this.getView());
        },

        // Processing when the Save button is pressed.
        onSave: function () {
            const oView = this.getView();

            // If the save button is pressed once and a validation error occurs,
            // the error message remains in the UI5 standard message model and is cleared before validation.
            this._validator.removeErrors(oView);
            // If there is a communication error such as OData, the error message remains in the UI5 standard message model
            // and should be cleared before validation.
            this.removeAllTechnicalMessages();

            // Validation is performed on arguments and their subordinate controls.
            // Also check hasErrorMessages to pick up errors due to UI5 standard validation.
            if (!this._validator.validate(oView, {isDoConstraintsValidation: true}) || this.hasErrorMessages()) {
                // Display error message dialog.
                this.showValidationErrorMessageDialog();
                return;
            }
        }
    });
});

 

item correlation validation example

view:

 

<mvc:View
    ...
    xmlns="sap.m">
    ...
    <Label text="{i18n>label.fromDate}" />
    <DatePicker
        id="fromDate"
        value="{
            path: '{xxx>/fromDate}',
            type: 'sap.ui.model.type.Date'
        }"
        valueFormat="yyyy-MM-dd"
        displayFormat="yyyy/MM/dd"
        required="true" />
    <Label text="{i18n>label.toDate}" />
    <DatePicker
        id="toDate"
        value="{
            path: '{xxx>/toDate}',
            type: 'sap.ui.model.type.Date'
        }"
        valueFormat="yyyy-MM-dd"
        displayFormat="yyyy/MM/dd"
        required="true" />

 

Controller:

 

// this.getRouter().getRoute("xxx").attachMatched(this._onRouteMatched, this); in the onInit method.
_onRouteMatched: function () {
    const oView = this.getView();

    // Validations other than required input checks should be displayed as errors on focus out as in the UI5 standard validation.
    this._validator.registerValidator(
        // ID to identify the function of the second argument, which should be a string unique within the Validator instance.
        "validateFromToDate",
        // Pass a validation function, which should return true if OK and false if NG.
        // The function is passed the control array passed as the fourth argument.
        ([oFromDate, oToDate]) => {
            const dFromDateValue = oFromDate.getDateValue();
            const dToDateValue = oToDate.getDateValue();
            // Required checks are done separately, so the only error here is if both are entered and the value is invalid.
            return !(dFromDateValue && dToDateValue && dFromDateValue.getTime() > dToDateValue.getTime());
        },
        // Message or array of messages to display in case of validation errors
        [
            this.getResourceText("message.dateBeforeDate", this.getResourceText("label.fromDate"), this.getResourceText("label.toDate")),
            this.getResourceText("message.dateAfterDate", this.getResourceText("label.toDate"), this.getResourceText("label.fromDate"))
        ],
        // Control or array of controls to be validated
        [oView.byId("fromDate"), oView.byId("toDate")],
        // The function of the second argument is executed after the validation of the control passed here.
        // This allows control over the order in which error messages are displayed
        oView.byId("toDate")
    );
}

 

For detailed usage and API documentation, see https://www.npmjs.com/package/@learnin/ui5-validator

I hope this helps you.

Labels in this area