Search code examples
javazk

How can I filter pasted values in intbox?


I have an intbox that is accepting any text value when it is pasted. I don't want to disable control+c values in this intbox so how can I make it regect char values pasted?

Some code:

<intbox mold="rounded" id="intbxNumeroDaConta" width="90px" />

Some pictures:

intbox

intbox with pasted value


Solution

  • If you paste a non-digital text, you shall see the validation error box when you blur the focus. This will hint users to fix their value.

    The solution below works for chrome, firefox, IE 11 or above

    <zk xmlns:h="client/attribute">
    avoid pasting non-number characters
        <intbox h:onPaste="preventPastingNonDigital(event)" />
    <script><![CDATA[
    function preventPastingNonDigital(e){
        var pastedText = e.clipboardData ? e.clipboardData.getData('text') //chrome, firefox
         : window.clipboardData.getData('text'); //ie11
    
        if (!new RegExp('^[0-9]+$').test(pastedText)){
            e.preventDefault();
        }
    }
    ]]></script>
    </zk>
    

    ref: https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/getData

    For older IE, they don't support onPaste, so please refer to JavaScript get clipboard data on paste event (Cross browser)