0

I want to write a validation for a textarea to prevent to type some words, well for example if you type Viber on textarea it will remove that and then alert, my problem is this code only work when you type viber first! if you type for ex: I like Viber, it doesn't work, i want to find viber everywhere in textarea and remove it, and second problem is i want to do this with all type of text in lowercase and uppercase, VIBER, viber, Viber, ViBeR and etc... can i do this?

$('textarea').keyup(function() {
  var val = this.value;
  var my = $(this).val();
  if ( val.indexOf('viber') == 0 ) {
 $(this).val($(this).val().split(my).join(""));
      alert("viber not allowed");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<textarea></textarea>

JSFiddle

Pedram
  • 15,766
  • 10
  • 44
  • 73

2 Answers2

4
$('textarea').keyup(function() {
    if ($(this).val().toLowerCase().indexOf('viber') != -1) {
        $(this).val($(this).val().replace(/viber/i, ''));
        alert('never say "Viber" again!');
    }
});

And pay attention to the String.indexOf - it returns index of the first match or -1 if it didn't find anything. In your case, you're checking for zero - it's wrong because zero means that it finds first occurence in the begginning of string.

1
  $('textarea').keyup(function() {
  var val = this.value.toLowerCase();
  var my = $(this).val();
  if ( val.indexOf('viber') != -1 ) {
 $(this).val($(this).val().split(my).join(""));
      alert("viber not allowed");
  }
});

http://jsfiddle.net/0g5kxbbh/2/

sinisake
  • 11,240
  • 2
  • 19
  • 27