如何防止javascript中的非字母数字输入? [英] How to prevent non-alphanumeric input in javascript?

查看:82
本文介绍了如何防止javascript中的非字母数字输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$("#user").keyup(function(e){ 
    var regx = /^[A-Za-z0-9]+$/;
    if (!regx.test('#user')) 
    {$("#infoUser").html("Alphanumeric only allowed !");}
);}

#user 是一个文本输入,我想要如果用户输入除字母和数字之外的任何内容,则显示警告。

在上述情况下,无论键入什么都会出现警告。

#user is a text input, and I want to diplay a warning if user enters anything except letters and numbers.
In the above case, the warning is present whatever is typed.

推荐答案

更改:

if (!regx.test('#user')) 

if (!regx.test( $(this).val() ) ) 

执行:

$("#user").keyup(function(e){     
    var str = $.trim( $(this).val() );
    if( str != "" ) {
      var regx = /^[A-Za-z0-9]+$/;
      if (!regx.test(str)) {
        $("#infoUser").html("Alphanumeric only allowed !");
      }
    }
    else {
       //empty value -- do something here
    }
});

JS Fiddle 示例

这篇关于如何防止javascript中的非字母数字输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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