Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexOf() function to return a -1 value

Tags:

javascript

I have a script that I'm trying to get working. Basically, what I'm trying to do is prevent someone from entering in special characters in to a field.

the function I have is as follows:

var iChars = "!@#$%^&*()+=[];,./{}|<>?;";
if (field1.value.indexOf(iChars) !=-1)

  { 
    alert ("problem")
  }

The issue I'm having is that the field is searching for the exact match to the iChars var instead of matching any single value. For example if I create a var test ="one" and enter "one" into the field, it returns with the error, but if I enter "o" into the field, it does not return anything and just passes through to the next portion of the script - but if i entered "none" or "oneeee" it would push the error through.

Any help on fixing this? I tried looking into arrays for indexOf but didn't really understand it, so if you are going to suggest it can you please explain in as much detail as possible.

Thanks

like image 707
SorryEh Avatar asked Jan 17 '23 00:01

SorryEh


2 Answers

You could use...

var value = field1.value;

for (var i = 0, length = value.length; i < length; i++) {
    if (iChars.indexOf(value.charAt(i)) != -1) {
       alert('Problem!');
       break;
    }
}
like image 182
alex Avatar answered Jan 28 '23 10:01

alex


The problem is you are looking for the index of the entire iChars string in the user input. What you actually want to do though is see if any char in iChars is in the input string. To do this use a for loop

var iChars = "!@#$%^&*()+=[];,./{}|<>?;";
var i;
for (i = 0; i < iChars.length; i++) {
  if (field1.value.indexOf(iChars[i]) !== -1) {
    alert("problem");
    break;
  }
}
like image 38
JaredPar Avatar answered Jan 28 '23 10:01

JaredPar