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
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;
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With