TextBox验证问题

时间:2016-09-28 12:15:28

标签: javascript asp.net

我有一个文本框,其javascript函数声明如下

<asp:TextBox ID="TextBox1" runat="server" onKeyUp="javascript:Count(this);" TextMode="Number"></asp:TextBox>
  

                           function Count(text) {
                               //asp.net textarea maxlength doesnt work; do it by hand
                               var maxlength = 4; //set your value here (or add a parm and pass it in)
                               var object = document.getElementById(text.id)  //get your object
                               if (object.value.length > maxlength) {
                                   object.focus(); //set focus to prevent jumping
                                   object.value = text.value.substring(0, maxlength); //truncate the value
                                   object.scrollTop = object.scrollHeight; //scroll to the end to prevent jumping
                                   return false;
                               }
                               return true;
                           }

我还将TextBox的TextMode属性设置为Number,但我仍然可以输入Alphabet“e / E”,并且在输入此特定字母时,我的javascript函数也未被调用。我该如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

试试这个。您可以使用多种数据类型来验证输入。您只需使用MaxLength属性将字符限制为4。

<asp:TextBox ID="TextBox1" onkeyup="checkString(this, 'INT')" MaxLength="4" runat="server"></asp:TextBox>

<script type="text/javascript">
    function checkString(inputID, inputType) {
        if (inputID.value != "") {
            if (inputType == "NUMERIC") {
                validChars = "0-9,.";
            } else if (inputType == "INT") {
                validChars = "0-9";
            } else if (inputType == "HASHTAG") {
                validChars = "a-z0-9-_#";
            } else if (inputType == "ALPHA") {
                validChars = "a-z";
            } else {
                validChars = "a-z0-9";
            }

            var regexp = new RegExp("[" + validChars + "]+", "ig");
            var matches = inputID.value.match(regexp);

            if (matches == null) {
                inputID.value = "";
            } else if (matches.length != 0) {
                inputID.value = matches.join("");
            }
        }
    }
</script>