如何验证只接受第一个字母作为字符&保留为javascript中的数字

时间:2016-08-13 11:25:47

标签: javascript asp.net validation

我想验证仅首先作为角色和文字的文本框。保留数字&不应该接受特殊字符。

<asp:TextBox ID="txtSlip" runat="server" CssClass="smalltextbox" PlaceHolder="Slip" Width="80px" OnKeypress="javascript:return FirstChar(event,this.value);" MaxLength="6" />

//First Letter Only Charactor Remaining Numbers
function FirstChar(event) {
var firstChar = (event.which) ? event.which : event.keyCode
if (firstChar <= '9' && firstChar >= '0') {
    //do your stuff
    return true;
}
return true;
}

例如:&#34; A00001&#34;像这样.. 但它对我不起作用..任何人都有所帮助,提前谢谢......

3 个答案:

答案 0 :(得分:1)

function FirstChar(event,val) {
var length=val.length;
 var firstChar = (event.which) ? event.which : event.keyCode;
if(length!=0)
{

       // console.log(firstChar);
        if (firstChar >= '48' && firstChar <= '57') {

            return true;
        }else
        {
        return false;
        }
}else
{

        if (firstChar >= '48' && firstChar <= '57') {

            return false;
        }else
        {


        return true;
        }

}
}

答案 1 :(得分:1)

我在Sathiya saravana Babu回答的帮助下找到答案

 function FirstChar(event, val) {
var length = val.length;
var firstChar = (event.which) ? event.which : event.keyCode;
if (length != 0) {
    var firstChar = (event.which) ? event.which : event.keyCode;
    if (firstChar >= '48' && firstChar <= '57') {

        return true;
    } else {

        return false;
    }
} else {

if (length == 0) {
    var firstChar = (event.which) ? event.which : event.keyCode;
    if ((firstChar >= '65' && firstChar <= '90') || (firstChar >= '97' && firstChar <= '122')) {

        return true;
    } else {

        return false;
    }
    return true;
}
}
}

谢谢大家,它的工作正常......

答案 2 :(得分:1)

 function FirstChar(event, val) {
     var length = val.length;

     if (length != 0) {
         var firstChar = (event.which) ? event.which : event.keyCode;
         console.log(firstChar);

         if (length != 1) {

             if (firstChar >= '48' && firstChar <= '57') 
             {
                 return true;
             } else 
             {
                 return false;
             }
         } 
       else 
       {
             if (firstChar <= '48' && firstChar >= '57')
             {
                 return true;
             } else 
             {
                 return false;
             }
         }
     } 
     else 
     {
         return true;
     }
 }

请检查此修改版Sathiya saravana Babu答案。