检测输入元素JS中是否输入了特殊字符 [英] Detect if special characters entered in input element JS

查看:612
本文介绍了检测输入元素JS中是否输入了特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JS,如何检测特殊字符是否在输入字段中输入?

Using JS, how can I detect if a special character is entered into an input field as it's typed?

编辑:特殊字符定义为非alpha /数字字符

Special character being defined as non-alpha/numeric character

编辑(2):

如果它能帮助别人,

HTML

< input type =textid =username name =usernamevalue =/>

JS / jquery

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);      
         }  
    })


推荐答案

在输入的keyup事件的事件处理程序中使用以下内容。

Use the following in an event handler for the input's keyup event.

function hasNonStandard(inputElem) { 
    return /[^\w]/.test(inputElem.value);
}

如果上述代码返回true,表示非数字或字符已输入到输入中。您可以查找正则表达式以更好地定义所需的内容。 \w还包含下划线,因此您可能不想要。

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.

这篇关于检测输入元素JS中是否输入了特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆