文本框接受字符&数字或字母但不仅仅是数字

时间:2016-02-15 08:05:06

标签: javascript regex

我想在可以接受的文本框上进行javascript验证。

一个。人物
  湾带数字的字符

  

它不应该只接受数字

例如我想要的东西: -

Abc123 A7组织

但我不想要; -

333333 2222222

此外,也不允许使用特殊字符

我尝试了以下js功能,但它无法正常工作

function NumersWithCharValidation() {
    var textBoxvalue = document.getElementById('txtNameOfFirm').value;
    alert(textBoxvalue);
    if (textBoxvalue.match("/^(?![0-9]*$)[a-zA-Z0-9]+$/")) {
        alert('Good to go');
    }
    else {
        alert('Only Numbers are not allowed');
    } 
}

<input id="txtNameOfFirm" runat="server" onkeypress="return NumersWithCharValidation();" maxlength="200" type="text" width="65%" />

请提出错误的建议

3 个答案:

答案 0 :(得分:2)

将方法更改为

function NumersWithCharValidation(thisObj) {
    var textBoxvalue = thisObj.value;
    if ( textBoxvalue.length > 0 && isNaN( textBoxvalue ) && !textBoxvalue.match( /\W/ ) ) 
    {
        alert('Good to go');
    }
    else 
    {
        alert('Only Numbers are not allowed. Special characters are also not allowed' );
    } 
}

<input id="txtNameOfFirm" runat="server" onkeypress="return NumersWithCharValidation(this);" maxlength="200" type="text" width="65%" />

isNaN( "textBoxvalue" )将检查该值是否为纯数

textBoxvalue.match( /\W/ )检查值

中是否有任何特殊字符

答案 1 :(得分:0)

像这样的正则表达式怎么样?字母的正向前瞻,它适用于您的示例输入。

if (textBoxvalue.match("/^(?=[a-zA-Z]+)[\w\s,]*$/")) { alert('Good to go'); } else { alert('Only Numbers are not allowed'); }

答案 2 :(得分:0)

这不允许用户再输入任何

jQuery("#txtNameOfFirm").keypress(function (event, ui)
{ return NumersWithCharValidation(event) });

function NumersWithCharValidation(evt) {

    if (jQuery("#txtNameOfFirm").val().match(/^[0-9]+$/) == null)
    { return true; } else { return false; }
}
相关问题