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: 
antonette_oberholster
Active Contributor
108,139

Hallo Guys

Today I would like to show you how to do front end user input validations in SAPUI5.

How to show a user that a field is mandatory

You know those little red stars that we all know indicates a required field? Well we can do this in SAPUI5 as well.

The trick is to remember that this is usually indicated in the label, not the control

Example:

Use the “required” property to indicate that a control is mandatory.

tfdMineManager = new sap.ui.commons.TextField({
      id : "tfdMineManagerID",
      required : true,
});

But you won’t see anything yet, you have to link the control to a label using the “labelFor” property
  
lblMineManager = new sap.ui.commons.Label({
      text : "Mine Manager Section:",
      labelFor : tfdMineManager,
});

Now you will see the infamous little red star

This does not do any actual validation, it merely shows the user that this is a required field.

How to force the user to enter a value in a mandatory field

There is this awesome thing called Value State, which is available with most of the input controls.

Example:

//View
tfdMineManager = new sap.ui.commons.TextField({
      id : "tfdMineManagerID",
      required : true,
      change : function() {
            if (this.getValue() === "") {
                  this.setValueState(sap.ui.core.ValueState.Error);  // if the field is empty after change, it will go red
            }

            else {
                  this.setValueState(sap.ui.core.ValueState.None); // if the field is not empty after change, the value state (if any) is removed
            }
      }
});

What if I only want to show a warning?

Sometimes there are grey (or yellow) areas that we have to cater for. In this case we use the Warning value state.

You can make use of any of the following vlaue states :

I want to validate a numeric field

This is a common requirement, but you can replace the function with whatever your validation check should be.

Example:

var testPreCalibration = sap.ui.getCore().getControl("PreCalibration").getValue();
if ( ! sap.ui.controller(<my controller>).isNumberFieldValid(testPreCalibration) ){
      sap.ui.getCore().getControl("PreCalibration").setValueState(sap.ui.core.ValueState.Error);
}

isNumberFieldValid : function(testNumber){
      var noSpaces = testNumber.replace(/ +/, '');  //Remove leading spaces
      var isNum = /^\d+$/.test(noSpaces); // test for numbers only and return true or false
      return isNum;
};

What do you do for controls that don’t support value states?

Not all of the input controls have value states. An example of this would be the DateTimeInput control . . . . .setValueState does nothing for this control . . . .

Let me introduce you to my dear friend . . . . CSS. 

Without too much coding we can create a CSS class for this control.

Example :

//Index
.myTimeErrorValueState input{
      border-width: 1px;
      border-style: Solid;
      border-color: #CC0000;
      background-color: #FFDDD9;
}

.myTimeWarningValueState input{

     border-width: 1px;
      border-style: Solid;
      border-color: #CC5200;
      background-color: #FFFFCC;
}

//Controller for error
var testTotalTime = sap.ui.getCore().getControl("TotalTime").getText();
if ( createTotalTime == "0" ){
      sap.ui.getCore().getControl("StartTime").addStyleClass("myTimeErrorValueState");
      sap.ui.getCore().getControl("StopTime").addStyleClass("myTimeErrorValueState");
};

//Controller for warning
var testStart = sap.ui.getCore().byId("StartTime").getDateValue();
var testStop = sap.ui.getCore().byId("StopTime").getDateValue();
if ( start > stop ){
      sap.ui.getCore().getControl("StartTime").addStyleClass("myTimeWarningValueState");
      sap.ui.getCore().getControl("StopTime").addStyleClass("myTimeWarningValueState");
};

What if you need to display a message to explain to the user why the fields are going red ?

You could trigger an alert or message to fire with the validation. We all have a few validations in our UI’s so a bunch of alerts popping up when you click submit just won’t do.

How do we handle all the validations in a single popup? Our validations only kick in after the user clicks submit.

We created a table that lists all the errors with a reason for the error/warning in addition to the red and yellow fields.

Example :

//controller
var errorData = [];
var errorExist = false;
var warningExist = false;

var testShiftWorked = sap.ui.getCore().getControl("ShiftWorked").getValue();
if ( ! sap.ui.controller(<my controller>).isTextFieldValid(testShiftWorked)){
      errorExist = true;
      sap.ui.getCore().getControl("ShiftWorked").setValueState(sap.ui.core.ValueState.Error);
      errorData.push({ field : "Shift Worked",
             text : "Cannot be empty",
             type : "Error",
             icon : "sys-cancel-2"});
}

//repeat the above for all your validations

if ( errorExist || warningExist ){
      var errorDialog = new sap.ui.commons.Dialog({
            modal: true,
            inverted: false,
            title: "Data Validation",
            closed: function (oEvent) {
                   this.destroyContent()}
});
  
var errorTable = new sap.ui.table.Table({
       editable : false,
       id : "errorTableId",
       width : "550px",
       visibleRowCount: 5,
       firstVisibleRow: 0,
       selectionMode: sap.ui.table.SelectionMode.None,
       navigationMode: sap.ui.table.NavigationMode.Paginator,  
});
      
errorTable.addColumn(new sap.ui.table.Column({
       editable : false,
       label : new sap.ui.commons.Label({ text : "Icon" }),
       template : new sap.ui.core.Icon({src : "{icon}"}),
       width : "40px",
       hAlign : "Center",
       resizable : false,
}));
  
errorTable.addColumn(new sap.ui.table.Column({
       editable : false,
       label : new sap.ui.commons.Label({
       text : "Type" }),
       template : new sap.ui.commons.TextView().bindProperty("text", "type"),
       width: "60px",
       resizable : false,
}));
  
errorTable.addColumn(new sap.ui.table.Column({
       editable : false,
       label : new sap.ui.commons.Label({
       text : "Screen Field" }),
       template : new sap.ui.commons.TextView().bindProperty("text", "field"),
       width: "130px",
       resizable : false,
}));
  
errorTable.addColumn(new sap.ui.table.Column({
       editable : false,
       label : new sap.ui.commons.Label({
       text : "Message" }),
       template : new sap.ui.commons.TextView().bindProperty("text", "text"),
       width: "300px",
       resizable : false,
}));
     
errorDialog.addContent(errorTable);  
var errorModel = new sap.ui.model.json.JSONModel();
errorModel.setData({modelData: errorData});
errorTable.setModel(errorModel);   
errorTable.bindRows("/modelData"); 
  
if ( ! errorExist && warningExist ){
       var errorAccept = new sap.ui.commons.Button({
             text: "Continue",
             icon : sap.ui.core.IconPool.getIconURI("accept"),
             width: "75px",
             press: function (oEvent) {
                   oEvent.getSource().getParent().close();
                   sap.ui.controller(<my controller>).goToMainActionView(inAction, false);
              }
       }); 
       errorDialog.addButton(errorAccept);
}  
  
var errorCancel = new sap.ui.commons.Button({
       text: "Back",
       icon : sap.ui.core.IconPool.getIconURI("nav-back"),
       width: "75px",
       press: function (oEvent) {
             oEvent.getSource().getParent().close();
             return false;
       }
});


errorDialog.addButton(errorCancel);  
errorDialog.open();

}
else {
      return true;
}

Using a Tooltip to tell users what the requirement is

Here you can find a demo of how you can use RichTooltip to help users: SAPUI5 SDK - Demo Kit

Hope this makes your SAPUI5 validations a bit easier.

If you have any suggestions, please feel free to share

Regards
Antonette

19 Comments
Labels in this area