Reputation: 4424
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;
}
});
}
}
Upvotes: 4
Views: 8217
Reputation: 10577
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;
}
}
Upvotes: 3
Reputation: 1158
This will Work of Past event only, you can change it for other events. It will restrict a user to Past '=' in the input field
$(function(){
$("#textInput").bind('paste', function(e) {
var ctl = $(this);
setTimeout(function() {
//Do whatever you want to $(ctl) here....
var bla = $('#textInput').val();
if (bla.indexOf('=') > -1){
alert("= not allowed");
$( '#textInput' ).val(null) ;
e.preventDefault();
return false;
}
}, 100);
});
});
Upvotes: 0
Reputation: 417
In addition to "keydown" event. you should use "paste" event to handle copy paste
$('#textbox').on("paste", function(e) {
if (event.keyCode === 187)
{
console.log("blocked.");
event.preventDefault();
return false;
}
});
or try using
$ ('#textbox').bind("paste", function (e) {
if (event.keyCode === 187)
{
console.log("blocked.");
event.preventDefault();
return false;
}
});
Upvotes: 2