Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html input validation that works when using paste

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?

like image 505
Suzi Larsen Avatar asked Sep 14 '15 08:09

Suzi Larsen


2 Answers

You have to do 2 things:

  1. Bind paste event (as is already mentioned above)
  2. Fix your regex that allows characters in the range between @ 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.

enter image description here

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"/>
like image 65
Wiktor Stribiżew Avatar answered Sep 29 '22 05:09

Wiktor Stribiżew


$("#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

like image 21
sunil Avatar answered Sep 29 '22 07:09

sunil