【问题标题】:TextBox validation Issue文本框验证问题
【发布时间】:2016-09-28 12:15:27
【问题描述】:

我有一个文本框和它的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,但我仍然可以输入字母“e/E”,并且在输入这个特定的字母时,我的 javascript 函数也不会被调用。我该如何解决这个问题。

【问题讨论】:

  • 您提供了错误的事件名称。它的 onkeyup 不是 onKeyUp...
  • 该函数也正常调用这个事件名称..
  • 你不想输入E/e吧???
  • 是的,我不想在文本框中输入“E”...

标签: javascript asp.net


【解决方案1】:

试试这个。您可以使用多种数据类型来验证输入。你可以使用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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多