0

I need to prevent adding scripts inside input fields.is there any way to prevent adding javascript codes in text fields/text areas?

function filter($event) {
    var regex = /[^a-zA-Z0-9_]/;
    let match = regex.exec($event.target.value);
    console.log(match);
    if (match) {
        $event.preventDefault();
    } else {
        return true;
    }
}
Dang Cao
  • 343
  • 2
  • 5
  • 13
gayan nad
  • 1
  • 2
  • Answered here https://stackoverflow.com/a/38085541/15866576 – Basta Jun 16 '22 at 09:05
  • So you want to stop the user from entering code that could potentially be run? Just sanitize it and replace any characters (parentheses, quotes, etc) with an encoded version instead of the literal string. – Jack Bashford Jun 16 '22 at 09:05
  • 1
    @Basta No, I don't think that's the case - I believe OP wants users to not be able to enter JS code in an input. – Jack Bashford Jun 16 '22 at 09:05
  • @JackBashford yes, I want to stop pasting or type javascript codes in Html input fields – gayan nad Jun 16 '22 at 09:14
  • Well then you have to have some way to detect if a string is a JavaScript code fragment (which is incredibly difficult, IMHO - just block specific characters like `()[]{};` and you should have some small success (not much you can do without them as far as I can think right now). – Jack Bashford Jun 16 '22 at 09:17
  • Does this answer your question? [Disable input conditionally (Vue.js)](https://stackoverflow.com/questions/38085180/disable-input-conditionally-vue-js) – Dang Cao Jun 16 '22 at 10:49

2 Answers2

0

You can sanitize the input by defining the blacklist regex which contains the patterns not allowed by the input and then replaced the part of input string with empty string if matched with the blacklist regex.

For now I just added a simple blackList regex (You can modify it as per your requirement) which will replace all the text comes between < and >. For Ex: If user enter <script>Hello</script> (This whole input text will get replaced with the empty string on keyup event.

const blackList = /<+>/ig

function sanitizeInput() {
  const inputStr = document.getElementById('inputStr').value;
  console.log('inputStr', inputStr)
  document.getElementById('result').innerHTML = inputStr?.replace(blackList, '')
}
<input type="text" id="inputStr" onkeyup="sanitizeInput()"/>

<div id="result"></div>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
0

here I have found the solution, I think it will work.

input.replace(/</g, "<").replace(/>/g, ">").replace(/=/g, "equal;");

hemant rao
  • 2,233
  • 2
  • 13
  • 14