I am using the following code for my validation that only allows letters and numbers and a few allowed characters.
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9%()#@-_& ]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
The only problem I am having is that if you copy and paste any un allowed characters then this doesn't prevent it. I know I have seen this done somewhere where it prevents the characters being pasted. Any thoughts?
You have to do 2 things:
paste
event (as is already mentioned above)@
and _
(all letters and some characters like ^
, [
... because you did not escape the hyphen, and it creates a range [@-_]
, which is valid (that is why you are not getting any error), but that is not what you expect.Here is the fixed code:
$('input').bind('keypress paste', function (event) {
var regex = /^[a-zA-Z0-9%()#@_& -]+$/;
var key = String.fromCharCode(event.charCode || event.which);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="txt1"/>
$("#textareaid").bind("paste", function(e){
// access the clipboard using the api
var pastedData = e.originalEvent.clipboardData.getData('text');
alert(pastedData);
} );
or you can try this way JQuery paste
There is one more way out, that you can do it so with onChange
or focusOut
events on textbox
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With