Thursday, February 27, 2014

Prevent copy/cut/paste in input fields

one of the requirements  we had for a certain application I've been working on was to prevent users from copying/pasting values from/into an input text field.
In this blog entry, I will show how we achieved the requested behavior.

basically, you can achieve the requested behavior using JavaScript.
include the following code snippet in your page:

<af:resource type="javascript">
          function eventCancel(evt) {
             AdfPage.PAGE.clearMessages(evt.getSource()._clientId);
              AdfPage.PAGE.addMessage(evt.getSource()._clientId, new AdfFacesMessage(AdfFacesMessage.TYPE_ERROR, "Error" , "context menu is disabled for this field" )) ;
          }

          function cancelCopy(evt) {
              if (((evt.getKeyCode() == AdfKeyStroke.C_KEY)||(evt.getKeyCode() == AdfKeyStroke.X_KEY))&&(evt.getKeyModifiers() & AdfKeyStroke.CTRL_MASK) > 0) {
                 AdfPage.PAGE.clearMessages(evt.getSource()._clientId);
                  AdfPage.PAGE.addMessage(evt.getSource()._clientId, new AdfFacesMessage(AdfFacesMessage.TYPE_ERROR, "Error" , "sorry cannot cut/copy" ));
                  evt.cancel();
              }
              if ((evt.getKeyCode() == AdfKeyStroke.V_KEY)&& (evt.getKeyModifiers() & AdfKeyStroke.CTRL_MASK) > 0) {
                    AdfPage.PAGE.clearMessages(evt.getSource()._clientId);
                  AdfPage.PAGE.addMessage(evt.getSource()._clientId, new AdfFacesMessage(AdfFacesMessage.TYPE_ERROR, "Error" , "sorry cannot paste" ));
                  evt.cancel();
              }
          }
        </af:resource>

then modify your input text field as shown below:
<af:inputText label="Label 1" id="it1" clientComponent="true">
          <af:clientListener type="keyDown" method="cancelCopy"/>
          <af:clientListener type="contextMenu" method="eventCancel"/>
        </af:inputText>

the above shows two client listeners:
1- is called on key down: which calls a function that test to see what the pressed key is and if the pressed key pressed is (X,C,V) and the control key is pressed, then  the edit operation is cancelled and an alert message is shown.
2- when the user right click on the field, the context menu event is cancelled, so no context menu will be shown, thus the user won't be able to use the edit operations.

Edited on 03/03/2014:
sorry, but it seems that the property ._clientId is an internal property of the javascript variable that should not be used by the developers. so, please use: evt.getSource().getId() instead.

No comments:

Post a Comment