I have an input field like below
<input type='text' class='keywordInput' value='' />
I want to restrict specific special characters to be input. I have written following code snippet but it does not work for the first time restricted character is input.
$(".keywordInput").on("keypress", function (e) {
var pattern = /[&/\\#,+(\);@$<>?^~%":\\*?<>|[\]'\{\}]/g;
if (pattern.test(e.currentTarget.value)) {
return false
}
});
I have created jsfiddle demo here. you can try pressing > it will input this character once and will not allow to write any character (even alphanumeric) afterwards.My Goal is to prevent inputing > on the first time also & I want to achieve it using jquery
var pattern = /[&/\\#,+(\);@$<>?^~%":\\*?<>|[\]'\{\}]/g;
const onKeydown = event => {
const match = event.key.match(pattern)
if (match !== null) {
event.preventDefault()
}
}
document.querySelector('.keywordInput').addEventListener('keydown', onKeydown)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<input type='text' class='keywordInput' value='' />