如何用jquery验证文本框只能输入字母数字和下划线

如题所述

由数字、26个英文字母或者下划线组成的字符串可用jquery正则表达式:  /^\w+$/,验证代码为:

 var reg = /^\w+$/;
 if(reg.test($("input:text").val()))
   // 验证通过
 else
   // 验证失败

下面给出实例演示:

    创建Html元素

    <div class="box">
    <span>请输入用户名,限定字母、数字或下划线的组合:</span><br>
    <div class="content">
    <input type="text"/>
    </div>
    <input type="button" value="验证">
    </div>

    设置css样式

    div.box{width:300px;padding:10px 20px;margin:20px;border:4px dashed #ccc;}
    div.box>span{color:#999;font-style:italic;}
    div.content{width:250px;height:50px;margin:10px 0;padding:5px 20px;border:2px solid #ff6666;}
    input[type='text']{width:250px;height:40px;padding:0 5px;border:1px solid #6699cc;}
    input[type='button']{height:30px;margin:10px;padding:5px 10px;}

    编写jquery代码

    $(function(){
    // 设置属性值
    $("input:button").click(function() {
    var reg = /^\w+$/;
    // 如果验证失败给出警告
    if(!reg.test($("input:text").val()))
    alert("用户名限定为字母、数字或下划线的组合");

    });
    })

    观察效果

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-07-28

由数字、26个英文字母或者下划线组成的字符串可用jquery正则表达式:
 /^\w+$/,验证代码为:
 var reg = /^\w+$/;
 if(reg.test($("input:text").val()))
   // 验证通过
 else
   // 验证失败
下面给出实例演示:
创建Html元素
<div class="box">
<span>请输入用户名,限定字母、数字或下划线的组合:</span><br>
<div class="content">
<input type="text"/>
</div>
<input type="button" value="验证">
</div>
设置css样式
div.box{width:300px;padding:10px 20px;margin:20px;border:4px dashed #ccc;}
div.box>span{color:#999;font-style:italic;}
div.content{width:250px;height:50px;margin:10px 0;padding:5px 20px;border:2px solid #ff6666;}
input[type='text']{width:250px;height:40px;padding:0 5px;border:1px solid #6699cc;}
input[type='button']{height:30px;margin:10px;padding:5px 10px;}
编写jquery代码
$(function(){
// 设置属性值
$("input:button").click(function() {
var reg = /^\w+$/;
// 如果验证失败给出警告
if(!reg.test($("input:text").val()))
alert("用户名限定为字母、数字或下划线的组合");
});
})
观察效果

第2个回答  2014-12-25
<input type="text" onkeyup="var reg = /^[\d\_a-zA-Z]+$/;if(!reg.test(this.value)) this.value='';" />
第3个回答  2014-12-25
用keycode应该可以实现限定只能输入数字和下划线本回答被网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网