I’m trying to prevent user from inserting * in a textbox.
This is what I was trying to do, but here it only detects * if this is the only inserted character. For example texts like: *, etc.
When allowed characters are mixed with *, then it cannot detect it. For example inputs such as: *hjh, etc..
and maybe how to make it replace only * with “” and not the whole field?
<script type="text/javascript">
function testField(field) {
var regExpr = new RegExp("[^*]");
if(!regExpr.test(field.value)) {
field.value = "";
}
}
</script>
<input type="text" id="searchGamesKeyword" class="searchGamesTextBox"
name="searchGamesKeyword" onblur="testField(this);" />
How about this:
Called from
onblur=testField(this)as shown in the question it will take the current value of the field and replace any and all asterisks with an empty string, leaving all other characters untouched. So, e.g.,"ab*cde*"would become"abcde".The
gon the end of/\*/gis a flag meaning to match globally – without this flag it would just replace the first match.The reason your code didn’t work is that your regex of
[^*]will match (i.e., return true from.test()) if there is a non-asterisk character anywhere in the string.