【问题标题】:Need client javascript function to check digit from textbox [closed]需要客户端javascript函数来检查文本框中的数字[关闭]
【发布时间】:2013-11-01 08:12:39
【问题描述】:

在客户端按钮单击事件中,我需要一个 javascript 函数来检查输入值是否全部为数字(0 到 9)。此外,还有一个标准是单选按钮选项。 如果用户选择是,则只允许数字输入。如果否,则输入任何字符。

我发现一些帖子正在检查数字并允许小数点,但对我来说,我不允许他们输入小数或破折号或其他任何内容。

有效字符必须是 0 到 9 的数字,并且计数必须是 10(我可以检查长度)。


Example of txtInput.Text
1234567890 -- return true
9781234567 -- return true
12.4567890 -- return false
123-567890 -- return false
123456789X -- return false

Code:
        function CheckFormInput() {
            var x = document.getElementById("<%#txtInput.ClientID%>").value;
            if (x != "") {
                if (document.getElementById("<%#rbtnYes.ClientID%>").checked) {
                    if (CheckInput(x)) return true;
                    else {
                        alert("Invalid Input!");
                        return false;
                    }
                }
                else {
                    return true;
                }
            }
            else {
                alert("Blank not allowed!");
                return false;
            }
        }

        function CheckInput(input) {
            //function to check length 10 & all chars in digit (0 to 9, no space, no dash, no decimal)
            if (document.getElementById("<%#rbtnYes.ClientID%>").checked) {
                if (input.length == 10) {
                // *** continue to check all in digit ***
                    return true;
                }
                else {
                    return false;
                }
            }
        }

html:-
<asp:Button ID="btnAddFile" runat="server" Text="Add Files" OnClientClick="return CheckFormInput()"  OnClick="btnAddFile_Click" />

感谢任何建议。提前致谢!

【问题讨论】:

  • 使用单个正则表达式很容易做到这一点。 Google 应该引出您需要的确切命令。
  • @Amy,那将使用模式属性...但是您可以在从按钮 onclick 调用的 javascript 函数上实现正则表达式。您也可以从 javascript 提交表单。这就是你想要的吗?
  • 你能展示任何代码示例吗? (不是当前没有真正逻辑的例子)
  • 您好,很抱歉造成混淆。我已经改写了我的问题。希望现在更好。
  • 尝试正则表达式:input.match(/^\d{10}/));

标签: c# javascript asp.net


【解决方案1】:
if( /^\d+$/.test(val) && val.length == 10){

alert("digits only, 10 chars long");

}

 if(!isNaN(parseInt(val)) && val.length == 10){
alert("digits only, 10 chars long");
}

html:

<input type="text" maxlength="10">  

【讨论】:

  • 此答案不会阻止长度小于 10 位的值
  • @jasonscript 抱歉 :) 就是这样!
  • 嗨,dllhell。我使用了第一个代码并且它的工作。谢谢你的时间。祝您度过愉快的一周!
【解决方案2】:

使用这个

  <input type="text" pattern="[0-9]{10}">  

【讨论】:

  • 我还需要在按钮单击和选择单选按钮时触发检查功能。
猜你喜欢
  • 2012-08-05
  • 2011-11-07
  • 2021-07-26
  • 1970-01-01
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
  • 2011-09-09
相关资源
最近更新 更多