问题
Using JS, how can I detect if a special character is entered into an input field as it's typed?
EDIT: Special character being defined as non-alpha/numeric character
EDIT(2):
If it helps anyone else, here's what I came up with:
HTML
<input type="text" id="username" name="username" value=""/>
JS/jquery
$("#username").keyup(function() {
var regExp = [document.getElementById("username").value];
for(i = 0; i < regExp.length; i++){
var regExp = new RegExp(/[^A-Za-z0-9_]/).test(document.getElementById("username").value);
}
})
回答1:
Use the following in an event handler for the input's keyup event.
function hasNonStandard(inputElem) {
return /[^\w]/.test(inputElem.value);
}
If the above code returns true, that means a non digit or word character has been entered into the input. You can lookup regular expressions to better define what you want. \w also includes underscores so you may not want that.
来源:https://stackoverflow.com/questions/17181066/detect-if-special-characters-entered-in-input-element-js