Rahul Rahul - 4 months ago 6x
Javascript Question

CRTL+V (Paste) function automatic formatting in JavaScript asp.net

In my current project, I have a textbox where the user will enter some numeric ID (like a product ID) -- For example:


I want to have a JavaScript in my aspx page that, when a user presses Ctrl+V to paste in text, will format that text irrespective of the text's present format.

For example, if the text is in formatted like
then the function will format it to


Tried your Suggetion but it's not working. I tried like this way... below code sample

<asp:TextBox ID="TextBox1" runat="server" Text="" ></asp:TextBox>
<br />
<br />

<script language="JavaScript" type="text/javascript">

var tb = document.getElementById("TextBox1");
tb.OnTextChanged = function () {

this.value = this.value.replace("---", "-");


It's erroring out saying

Microsoft JScript runtime error: Unable to set value of the property
'OnTextChanged': object is null or undefined


To update a textbox whenever its text is change, you can use the "onchange" event (just note that the change won't happen until focus leaves the textbox)

First, give your textbox a unique id—asp.net version 4 has features that allow you to give form elements id's that won't be "messed with"—then set the onchange event.

var tb = document.getElementById("textBoxId");
tb.onchange = function() {
   //I think you want:
   this.value = this.value.replace("---", "-");


You can catch the keyup event, and check to see if the user has just hit control-v. If so, you can modify the textbox's current value. Just note that this will not work if the user pastes by right clicking.

The best way to handle this is with the onchange event, which will work no matter how the textbox is changed.

   document.getElementById("tb").onkeyup = function (e) {
       var key = e.which || e.keyCode;
       if (e.which === 86 && e.ctrlKey)
           alert("you pasted " + this.value);