Prevent the user from writing specific words in <textarea>

I watched a tutorial from a developpp guy from youtube. I want people not to write bad words in my text area from my form.

But I want them not to write a few words, and not just one, this tutorial does not explain this, and I'm trying to find a way without success, can someone explain to me?

this is actual javascript

HTML

<textarea class="ta" id="ta" name="ta" onkeyup="clean('ta')" onkeydown="clean('ta')" placeholder="A good word for a good word"></textarea>

JAVASCRIPT

<script type="text/javascript">
        function clean(el){
var textfield = document.getElementById(el);
var regex = /fuck/gi;
if(textfield.value.search(regex) > -1) {
    textfield.value = textfield.value.replace(regex, "");
    }
}
</script>

Thanks for your time guys!

+4
source share
2 answers

You can create your regular expression with a few | (pipes):

textfield.value = textfield.value.replace(/badword1|badword2|badwordn/gi , "" );
+6
source

Well, the easiest way to do this (for me) is probably to use the jQuery library to view keystrokes in a text box.

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

<textarea id="mytextArea" style="width:200px; height:300px"></textarea>

$(document).ready(function() {
  $('#mytextArea').keyup(function() {
    var textBoxValue = $(this).val();
    console.log(textBoxValue);

    var forbidden = [
      'fuck',
      'shit'
    ];

    for(var i = 0; i < forbidden.length; i++) {
      if(textBoxValue.search(forbidden[i]) > -1) {
        textBoxValue = textBoxValue.replace(forbidden[i], '');
      }
    }

    $(this).val(textBoxValue);
  });
});

https://jsfiddle.net/t1p27hv4/

, , "f uck", , , , , .

, , , , google it.

+1

Source: https://habr.com/ru/post/1691286/


All Articles