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:
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.
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.
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.