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?
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?
Share Improve this question edited Sep 14, 2015 at 8:59 Suzi Larsen asked Sep 14, 2015 at 8:51 Suzi LarsenSuzi Larsen 1,5005 gold badges18 silver badges32 bronze badges 3- add your code.......... – Pranav C Balan Commented Sep 14, 2015 at 8:51
- add code on keydown or keyup of the input field having the validation – aelor Commented Sep 14, 2015 at 8:52
- use $(element).on('paste',function(e) { // your validation code }) see stackoverflow./questions/6035071/… – Juned Lanja Commented Sep 14, 2015 at 8:55
2 Answers
Reset to default 4You have to do 2 things:
- Bind
paste
event (as is already mentioned above) - 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.
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./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