Search code examples
javascripthtmljspstruts-1

Client side form validation for Copy/Pastes via Right-Click


I'm using the following line (Struts1 syntax) to display a text field and allow some client side checks via Javascript.

<html:text styleId="myField" property="myProperty" onkeyup="function()" />

My intention is for a message to appear and a dropdown to disable whenever there is text entered into the form field (regardless of content). The onkeyup attribute works fine for all cases except for when the user pastes in text using mouse right-click.

It doesn't appear that onmousedown and onmouseup events notice right clicks. The same goes for onfocus.

onchange only makes the check when focus is lost, however the user can circumvent this by pasting data and clicking the form submit (same for onblur).

onmouseout somewhat works (I can break functionality) in IE8, but doesn't work at all in Chrome v41.0.2272.89

Has anyone encountered client-side form checks on Mouse-Right Click? I'd like to cover this use case across browsers and cannot count on the end user to always paste via keyboard shortcuts.


Solution

  • I went with a jQuery solution as suggested by Aleksandr M above in comments.

    Initially I had this function:

    $(document).ready(function(){
        $('#myField').bind("paste",function(e) {
            toggleFunction(); //preserve already existing function in use with other cases
        });
    });
    

    But then came to find that while the function would run following the user's paste, it would run prior to the text actually being pasted.

    Example:

    1. User pastes (Right-click > paste OR Ctrl+V);

    2. Function is called and executes, condition checks made

    3. Text is pasted.

    So instead I replaced the function call in the jQuery with my intended end result, making some additional changes elsewhere so that my assumptions are met.

    But those conditions aside, the below ends up doing what I needed.

    $(document).ready(function(){
        $('#myField').bind("paste",function(e) {
            document.getElementById("dropdownID").disabled = true;  
            document.getElementById("showMessage").style.visibility = "visible";    
        });
    });