Search code examples
formsvalidationinputcomboboxsapui5

UI5: Validate Whole Form's Required and Visible Fields for Null/Blank Values


onPress of submit button, I want to validate all SimpleForms' fields (ComboBox, Input, DatePicker, etc.) that are

  1. required &
  2. visible

to see if they are null or blank (""). If a targeted (required & visible) field is null/blank, set that control's state to "Error" and display an error message. If no targeted field is null/blank, pop up a success dialog box.


Solution

  • This method is automated so in the future, any fields added later will automatically be checked without need of manual additions to controller code.

    Controller code:

    requiredAndVisible: function(oControl) {
        if (typeof oControl.getRequired === "function") { //certain ctrls like toolbars dont have getRequired as a method, so we want to skim those out, else itll throw an error later in the next check
          if (oControl.getRequired() === true && oControl.getVisible() === true) {
            return oControl;
          }
        }
      },
    
      onSubmit: function() {
        var valid = true,
          oView = this.getView(),
          aFormInitial = oView.byId("formInitial").getContent(), // get all the controls of SimpleForm1
          aFormConfig = oView.byId("formConfiguration").getContent(), // get all controls of SimpleForm2
          aControls = aFormInitial.concat(aFormConfig), // combine the 2arrays together into 1
          aFilteredControls = aControls.filter(this.requiredAndVisible); // check each element if it required & visible using the 1st function. return only the controls that are both req'd & visible
    
        aFilteredControls.forEach(function(oControl) { // in resultant array, check each element if...  
          if (!oControl.getValue() || oControl.getValue().length < 1) { // its value is null or blank
            oControl.setValueState("Error");
            valid = false; // set valid to false if it is
          } else {
            oControl.setValueState("None");
          }
        });
    
        if (valid === false) {
          // **replace this code with w/e error handling code u want**
          oView.byId("errorMsgStrip").setVisible(true);
        } else if (valid === true) {
          // **replace this code with whatever success handling code u want**
          var oDialogConfirm = new sap.ui.xmlfragment("dialogID", "dialog.address.here", this);
          oDialogConfirm.open();
        }
      },