2

I want to ensure that user can't paste string with (. | ") how do i prevent it? I was doing research about keyboard key and it work when user type. but how do i prevent paste?

here is jsfiddle Testing here

Here is my java script

$("[name='search']").on({
keydown: function(e) {
    if (e.which === 32 || e.which === 220) {
        e.preventDefault();
        var v = this.value,
            s = this.selectionStart;
        this.value = v.substr(0, s) + '' + v.substr(s, v.length);
    }
     if (e.which === 55) {
        e.preventDefault();
        var v = this.value,
            s = this.selectionStart;
        this.value = v.substr(0, s) + '7' + v.substr(s, v.length);
    }
},


// Here is the paste function but i no sure how to write it

paste: function(e) {
    var s = this;
    setTimeout(function() {
        // here i no sure how to do it
    });
   }
});
Aruna
  • 11,959
  • 3
  • 28
  • 42
nonstop328
  • 629
  • 1
  • 6
  • 17

2 Answers2

3

Obligatory note: it seems you're attempting some client side validation. Before I answer, I'll point out that client side validation isn't very reliable—especially when security is involved—as anyone who knows their way around a js console can defeat it. See the question why is client-side validation not enough? for more. If you want to prevent improper characters from being entered, you'll have to do it server-side.

That being said, checking on the client side is handy and can save the user some time. The most reliable way to do this is with test() and a simple regular expression. You can then use that test with an if conditional to strip out the offending value using replace().

Coupled with your original code, it looks a bit like this:

function check(e){
    var expression = new RegExp(/[\.\|]/, "g");
    if (expression.test(e.target.value)){
        e.target.value = e.target.value.replace(expression, "")
    }
}

And you can call that function from the appropriate place in your $("[name='search']").on({ section. Also note that your expression could be any regex, allowing you to check for any character or combination characters. Regex is power.

You could just put lines 2-5 into the function called on paste, but having tested it in Safari and Chrome, it seems your best bet is probably going to be to call the check() function above after both a paste or a blur event. This is because pasting into an input doesn't always trigger a change event. There's some detail there in the jQuery docs for .on(), though trial and error are great too.

Putting all that together, I got the following:

function check(e){
    var expression = new RegExp(/[\.\|]/, "g");
    if (expression.test(e.target.value)){
        e.target.value = e.target.value.replace(expression, "")
    }
}

$("[name='search']").on({
    keydown: function(e) {...},
    paste: function(e){
        check(e)
    },
    blur: function(e){
        check(e)
    }
});

Hope this helps!


Tips for improvement: I would personally work on this a bit more to make the code more reliable and expressive, clean it up a bit, and potentially rethink my approach in general. Just for starters:

  1. Consider throwing an error and stripping out all the content from the input box rather than just removing the offending characters ".|" — changing a user's input without warning them is generally a bad move. Usually better to just remove everything.

  2. Remove the piece that prevents entry of certain characters. Again: someone with knowledge around the JS console can get around that in a heartbeat and you're just adding overhead by checking each key press. It's not a major problem, but it could be improved.

  3. Use a switch case statement to put all the check logic into one place and run it for all the appropriate events. You'd have to get fancy with the jQuery event listener and it might not be worth it, but I would investigate that if I was writing this code.

Community
  • 1
  • 1
justin
  • 1,528
  • 11
  • 26
  • @Aruna the sample I provided works in the context of the original code, I just truncated the original keypress handler for readability – justin Nov 17 '16 at 00:21
  • @justin please check the `paste` event whether its working. – Aruna Nov 17 '16 at 01:23
  • @Aruna what I am saying is I based my example on the original code, developed a working solution, and then copied it to my answer less the bit I truncated. As far as the scope of this question, any cross-browser compatibility fixes or troubleshooting on a misunderstanding of browser events seems a bit irrelevant. I'd love to help you with my answer, what exactly are you trying to understand with your questions? – justin Nov 17 '16 at 07:10
  • Your code won't work for the `paste` event. Please try to execute it. – Aruna Nov 17 '16 at 07:12
1

You can use setTimeout along with bind as below and remove the characters using regular expressions.

$("[name='search']").on({
    keydown: function(e) {
        if (e.which === 32 || e.which === 220) {
            e.preventDefault();
            var v = this.value,
                s = this.selectionStart;
            this.value = v.substr(0, s) + '' + v.substr(s, v.length);
        }
         if (e.which === 55) {
            e.preventDefault();
            var v = this.value,
                s = this.selectionStart;
            this.value = v.substr(0, s) + '7' + v.substr(s, v.length);
        }
    },
    
    paste: function(e) {
        var stopPaste = function(){
           this.value = this.value.replace(/[|\s]/g, '');
        };
                        
        setTimeout(stopPaste.bind(this), 1);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>Search: </span><input type="text" name="search" size="75" /></div>
Aruna
  • 11,959
  • 3
  • 28
  • 42