Detect if special characters entered in input element JS [closed]

拈花ヽ惹草 提交于 2019-12-13 09:22:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!