Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Prevent users from copy pasting a special character in input text?

In javascript how can i check if the users have '=' in the text they are pasting and prevent the text from being pasted in textbox. I found it a bit tricky. I am working on a vulnerability issue where users should not be allowed to enter = in input field where i have achieved to some extent where user cant enter in textfield but can copy paste which is an issue. Below is my code. Please help.

$(document).ready(function() 
{
    inPutCheckForText();
 });

function inPutCheckForText()
{
    fields = document.getElementsByTagName('input');
    for (index = 0; index < fields.length; ++index) 
    {
        fields[index].addEventListener("keydown", function(event) 
        {
            if (event.keyCode === 187) 
            {
                console.log("blocked.");
              event.preventDefault();
              return false;
            }
        });
    }
}
like image 263
sTg Avatar asked Oct 15 '25 15:10

sTg


1 Answers

I do it like this:

<input type="text" onpaste="validatePaste(this, event)"> 

                        

, and I call my function located inside <script> tags like:

function validatePaste(el, e) {
  var regex = /^[a-z .'-]+$/gi;
  var key = e.clipboardData.getData('text')
  if (!regex.test(key)) {
    e.preventDefault();
    return false;
  }
}
like image 156
pixel Avatar answered Oct 18 '25 05:10

pixel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!