Maninder
Maninder

Reputation: 1261

Copy paste not working in textbox in Firefox post numeric validation

I am validating a textbox that will allow only numeric values of fixed length. I have done workaround to allow certaing keys like backspace, delete, arrow keys etc and this is working fine.

I am not able to paste any text in the textbox as well as copy text from the textbox in Firefox. In chrome its working fine.

Here is the code I have written.

function validateTransactionId(event)
{
    var transactionId = document.getElementById('transactionId').value;
    var charCode = (event.which) ? event.which : event.keyCode;

    // Allow: backspace, delete, tab, escape, enter
    if ($.inArray(charCode, [46, 8, 9, 27, 13, 110]) !== -1 ||                
        // Allow: home, end, left, right
        (charCode >= 35 && charCode <= 39)) {
        return true;
    }

    if ((charCode < 48 || charCode > 57))
        return false;
                
    if (transactionId.length == 11)
        return false;

    return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Transaction ID" id="transactionId" 
      onkeypress="return validateTransactionId(event)" />

I want to enable copy paste in this textbox. Any help here will be much appreciated.

Upvotes: 1

Views: 810

Answers (1)

clarmond
clarmond

Reputation: 358

A few things to consider.

First, you may want to include the v character to account for Ctrl+V or Cmd+V for pasting.

if ($.inArray(charCode, [46, 8, 9, 27, 13, 110, 118]) !== -1

Secondly, if someone is pasting, the length may already be more than 11. So you need to change your if statement.

if (transactionId.length > 11) return false;

Third, if someone pastes a non-numeric string less than 11 characters, it will still accept it.

My suggestion would be instead of trying to validate individual key presses that you validate the value of the textbox. You can use a regular expression match to strip out non-numeric characters.

transactionId = transactionId.replace(/\D/g, "");

Upvotes: 1

Related Questions