Search code examples
javascriptcomboboxsapui5

How do i restrict the user input in ComboBox to only model data in SAPUI5


I have a scenario where i want to restrict user to only input text that is only loaded to the combobox as seen in this MultiComboBox example. [Take note that this is not my jsbin. please post your answer in this thread]

http://jsbin.com/sicixisozi/edit?html,js,output

in the above example, user is only allowed to enter characters that are present in the combobox, for example entering a 's' will prompt invalid entry and prevent user from typing. however, i'm not using the MultiComboBox but will be using the ComboBox instead and this function is not found in default SAPUI5 ComboBox

http://jsbin.com/xenidoh/embed?html,output

var mcb = new sap.m.ComboBox({  

as seen in above example, user are not restricted and are able to input anything to the combobox. any suggestion how i could implement the same feature in MultiComboBox to the ComboBox?


Solution

  • on the change event of the combo box check that the oComboBox.getSelectedkey() is not null or empty. If it is empty, it means that the user hasn't selected a correct value and so return an error.

    oComboBox.attachChange(function(oEvent){
              var newval = oEvent.getParameter("newValue");
              var key = oEvent.getSource().getSelectedItem();
    
    
              if (newval !== "" && key === null){
                oEvent.getSource().setValue("");
                oEvent.getSource().setValueState("Error");
              }else{
                oEvent.getSource().setValueState("None");
              }
    
          });
    

    or if you are using XML views - add the function to the change="" where oComboBox is your combobox.

    http://jsbin.com/vupehukena/1/edit?html,output