javascriptvalidationantisamy

javascript : How to prevent user from entering = in textbox?


I have a requirement where i have to prevent users from entering = in textbox in entire application to prevent vulnerability.

<input type="text"></input>

I have been using antisamy-1.4.4.xml and XSSFilter.java which takes care of quite a few vulnerability checks but does not check for '=' sign entered in textbox. Is there anyway i can do for a textbox that will be done for the entire application?


Solution

  • You could attach a listener to the input elements in the document, check if the user has pressed the = key, and if so, take an action.

    Something like this should work:

    const textInput = document.querySelector('input');
    textInput.addEventListener("keydown", function(event) {
        if (event.keyCode === 187) {
        	console.log("equals pressed");
            // Prevent default behaviour
            event.preventDefault();
            return false;
        }
    });
    <input type="text"></input>

    But I wouldn't rely on this as being "secure" since a user can override the JS behavior in their browser. You should still sanitize the input on the server-side.

    Update

    To handle the case where a user pastes something into the input field, you could intercept the pasted string and strip the illegal characters (equals sign in this case).

    Example:

    textInput.onpaste = function(e) {
        e.preventDefault();
        clipboardData = e.clipboardData;
      pastedData = clipboardData.getData('Text');
      textInput.value = pastedData.replace("=", "");
    }
    

    Or you could just e.preventDefault() to disable pasting altogether.