How to prevent users from writing some specific words in a text box - jQuery

Is it possible to prevent users from entering or using certain words in textboxwith JQueryor Javascript? For example, I have one textbox, and I do not want users to use words such as " Phone ", " Home ", " Address > ', etc. Please help.

+4
source share
4 answers

This may be an option.

var txtBox = $('#text-box');
var blackList =  ['Phone', 'Home', 'Address'];

function checkBlackList(str) {
  $.each(blackList, function(i, n) {
    if(new RegExp(n, "i").test(str)) {
      txtBox.val(txtBox.val().replace(new RegExp(n, "gi"), "xxx"))
    }
  })
}

txtBox.on('keydown', function(e) {
  checkBlackList(this.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea name="" id="text-box" cols="30" rows="10"></textarea>
Run code
+2
source

You can check if a string contains a specific word:

if (yourVariable.indexOf("phone") >= 0){
    alert('you may not use the word phone');
}

, .

var words = ['phone', 'home', 'address', 'bobba'];
for (i = 0; i < words.length; i++) {
    if (yourVariable.indexOf(words[i]) >= 0){
        alert('you may not use the word ' + words[i]);
    }
}

, , , , :

yourVariable.replace(words[i], 'xxx');

, : https://jsfiddle.net/jx8wd1br/1/

+2
<input type="text" id="txt" />

<script>
 $(document).ready(function(){
 $("#txt").on("keydown", function(){
   var text = $("#txt").val();
   if(text.contains("Phone")){
     $("#txt").val().replace("Phone", "");
    }
   if(text.contains("Home")){
     $("#txt").val().replace("Home", "");
    }
   if(text.contains("Address")){
     $("#txt").val().replace("Address", "");
    }
 });
});
</script>
+2
source

My suggestion is based on:

var forbiddenWords = ['Phone', 'Home', 'Address'];
$(function () {
  $('#myTxt').on('keyup', function(e) {
    forbiddenWords.forEach(function(val, index) {
      if (e.target.value.toUpperCase().indexOf(val.toUpperCase()) >= 0) {
        e.target.value = e.target.value.replace(new RegExp( "(" + val + ")" , 'gi' ), '');
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
    <input type="text" id="myTxt">
</form>
Run code
+1
source

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


All Articles