Ajmal Razeel Ajmal Razeel - 4 months ago 20
Javascript Question

how to prevent users from writing some specific words in a textbox - JQuery

Is it possible to prevent users from typing or using some specific words in a

textbox
using
JQuery
or
Javascript
? For example, I have a
textbox
and I don't want users to use words like 'Phone', 'Home', 'Address' etc. Please Help.

Answer

This might 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>

Comments