如何验证TextBox仅允许数字。

时间:2014-02-04 15:22:34

标签: c# asp.net visual-studio-2012

我需要一个只允许数字的文本框(在.aspx网页上 - ASP.NET C#Framework 4.5 - Visual Studio 2012)

这是我开始使用的,我转换为C# - 它主要起作用,但我相信由于框架修改,OnValidating部分在C#中不起作用:

以下是让我离开的原始网站:http://social.msdn.microsoft.com/Forums/en-US/4a2d7afa-a7d1-4886-9366-13786e7ddfd2/allow-only-numeric-entries-in-textbox?forum=vblanguage

这是最初的VB:

Public Class NumericTextbox  
Inherits TextBox  

Public Sub New()  
    mAllowedNumberStyles = Globalization.NumberStyles.Any  
    mCultureFormat = Globalization.CultureInfo.CurrentCulture.NumberFormat  
End Sub 

Private mAllowedNumberStyles As System.Globalization.NumberStyles  
Public Property AllowedNumberStyles() As System.Globalization.NumberStyles  
    Get 
        Return mAllowedNumberStyles  
    End Get 
    Set(ByVal value As System.Globalization.NumberStyles)  
        mAllowedNumberStyles = value  
    End Set 
End Property 

Private mCultureFormat As System.Globalization.NumberFormatInfo  
Public Property CultureFormat() As System.Globalization.NumberFormatInfo  
    Get 
        Return mCultureFormat  
    End Get 
    Set(ByVal value As System.Globalization.NumberFormatInfo)  
        mCultureFormat = value  
    End Set 
End Property 

Private mNumericValue As Double 
Public Property NumericValue() As Double 
    Get 
        Return mNumericValue  
    End Get 
    Set(ByVal value As Double)  
        mNumericValue = value  
        Text = mNumericValue.ToString  
    End Set 
End Property 

Protected Overrides Sub OnValidating(ByVal e As System.ComponentModel.CancelEventArgs)  
    MyBase.OnValidating(e)  
    If Not e.Cancel AndAlso TextLength > 0 Then 
        If Not Double.TryParse(Text, mAllowedNumberStyles, mCultureFormat, mNumericValue) Then 
            e.Cancel = True 
        End If 
    End If 
End Sub 

End Class 

这是我的相同代码的C#版本(很大程度上要归功于telerik Code Converter!) - onValidating中有3个错误。有关错误的详细信息,请参阅下面的最后一种方法(OnValdiating):

using System;
using System.Collections.Generic;
using System.Linq;
//using System.Web;



using Microsoft.VisualBasic;
//using System;
using System.Collections;
//using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace Clarity.Utilities
{
    public class NumericTextBox : TextBox
    {
        public NumericTextBox()
        {
            mAllowedNumberStyles = System.Globalization.NumberStyles.Any;
            mCultureFormat = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
        }

        private System.Globalization.NumberStyles mAllowedNumberStyles;
        public System.Globalization.NumberStyles AllowedNumberStyles
        { //get;set;}
            get { return mAllowedNumberStyles; }
            set { mAllowedNumberStyles = value; }
        }

        private System.Globalization.NumberFormatInfo mCultureFormat;
        public System.Globalization.NumberFormatInfo CultureFormat {
        //private System.Globalization.NumberFormatInfo mCultureFormat;
        //public System.IFormatProvider CultureFormat         {//get;set;}
            get { return mCultureFormat; }
            set { mCultureFormat = value; }
        }

        private double mNumericValue;
        public double NumericValue
        {
            get { return mNumericValue; }
            set
            {
                mNumericValue = value;
                Text = Convert.ToString(mNumericValue);
            }
        }

        // This part generates three errors -- 
        // 1) 'System.Web.UI.WebControls.TextBox' does not contain a definition for OnValidating'
        protected override void OnValidating(System.ComponentModel.CancelEventArgs e)
        {
            // 2) 'System.Web.UI.WebControls.TextBox' does not contain a definition for OnValidating'
            base.OnValidating(e);
            if (!e.Cancel && Text.Length > 0)
            {
                // 3) The best overloaded method match for 'double.TryParse(string, 
                //System.Globalization.NumberStyles, System.IFormatProvider, out double)' 
                //has some invalid arguments        
                if (!double.TryParse(Text, mAllowedNumberStyles, mCultureFormat, mNumericValue))
                {
                    e.Cancel = true;
                }
            }
        }

    }
}

    //=======================================================
    //Service provided by Telerik (www.telerik.com)
    //Conversion powered by NRefactory.
    //Twitter: @telerik
    //Facebook: facebook.com/telerik
    //=======================================================

4 个答案:

答案 0 :(得分:2)

如果您使用JQuery,则可以执行此操作。

$('#YourID').on('keypress', function (ev) {
        var keyCode = window.event ? ev.keyCode : ev.which;

        if ((keyCode < 48 || keyCode > 57) && keyCode != 46) {
            //codes for backspace, delete, enter            
            if (keyCode != 0 || keyCode != 8 && keyCode != 13) {
                ev.preventDefault();
            }
        }
    });

这将只允许数字,退格,删除和输入

答案 1 :(得分:2)

其他答案的替代方法是使用ASP.net Range Validator

它的一个例子是:

 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
 <asp:RangeValidator ID="RangeValidator1" runat="server" 
        ErrorMessage="RangeValidator" MaximumValue="10000" MinimumValue="0" ControlToValidate="TextBox1"
        Type="Integer"></asp:RangeValidator>
 <asp:Button ID="Button1" runat="server" Text="Button" />

验证器设置为检查0到10000之间的整数值。如果您还想要强制检查,也可以将它与RequiredField验证器结合使用。

答案 2 :(得分:1)

您可以使用正则表达式执行此操作

这将只允许数字或无数字:

System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$")

如果您想动态使用javascript或将其放在<input>标签内。

<input type="text" name="example" pattern="^[0-9]*$">

答案 3 :(得分:0)

http://forums.asp.net/t/1832924.aspx我找到了我的答案...所有的答案让我朝着正确的方向前进......有6种方法可以给这只猫皮肤贴身!感谢大家的信息!!

<script language="javascript" type="text/javascript">
// Except only numbers and dot (.) for salary textbox
function onlyDotsAndNumbers(event) {
    var charCode = (event.which) ? event.which : event.keyCode
    if (charCode == 46) {
        return true;
    }
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}
//Except only numbers for Age textbox
function onlyNumbers(event) {
    var charCode = (event.which) ? event.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

 // No alphabets for Emp No textbox
function noAlphabets(event) {
    var charCode = (event.which) ? event.which : event.keyCode
    if ((charCode >= 97) && (charCode <= 122) || (charCode >= 65) && (charCode <= 90))
        return false;

    return true;
}

Salary:<asp:TextBox ID="txtSalary" runat="server" onkeypress="return onlyDotsAndNumbers(event);"> </asp:TextBox><br />
Age:<asp:TextBox ID="txtAge" runat="server" onkeypress="return onlyNumbers(event);"></asp:TextBox><br />
Emp no:<asp:TextBox ID="txtEmpNo" runat="server" onkeypress="return noAlphabets(event);"></asp:TextBox>