ASP.Net TextBox控件只允许输入数字

1.1、在Asp.Net TextBox 控件的 OnKeyPress 事件中指定输入键盘码必须为数字:
<asp:TextBox ID="TextBox" runat="server" OnKeyPress="if(((event.keyCode>=48)&&(event.keyCode <=57))||(event.keyCode==46)) {event.returnValue=true;} else{event.returnValue=false;}" MaxLength="15"> </asp:TextBox>

注意:如果不允许输入小数点去掉“event.keyCode==46”这种情况

或者:<asp:TextBox ID="TextBox" runat="server" onkeyup='value=value.replace(/[^d]/g,'') ' onbeforepaste='clipboardData.setData('text',clipboardData.getData('text').replace(/[^d]/g,''))' MaxLength="15"> </asp:TextBox>

  类似方法一:
if(e.KeyChar!=8!Char.IsDigit(e.KeyChar)e.KeyChar!='.'){ e.Handled = true; } 
  类似方法二:
if ((e.KeyChar < 48 || e.KeyChar > 57) (e.KeyChar != 8) e.KeyChar!='.'){ e.Handled = true; }
  类似方法三:
if (!Char.IsNumber(e.KeyChar) !Char.IsPunctuation(e.KeyChar) !Char.IsControl(e.KeyChar)){ e.Handled = true;}
  解释:其中e.KeyChar是键盘输入的键对应的字符,IsDigit函数可以判断是否为0到9的数字,Chr(8)
  为退格键,当e.Handled为True时,程序认为该KeyPress事件已经被处理过了,文本框的内容也就不会发生变化
  如果文本需要输入小数的话,就要能够输入小数点.,而且小数点只能输入一次
  //IsNumber:指定字符串中位于指定位置的字符是否属于数字类别
  //IsPunctuation:指定字符串中位于指定位置的字符是否属于标点符号类别
  //IsControl:指定字符串中位于指定位置的字符是否属于控制字符类别
  注意: 这里是在输入时便限制其他类型的字符被写入 TextBox;
  就是说你不输入正确或你输入的不是数字我就不让你做其他任何工作!
  霸道吧? 呵呵, 如果你不喜欢这种方式, 下面有几种允许用户先随便输入,
  然后再判断, 如果不是整数, 我给你来个警告, 告诉你输入类型不正确, 请重新输入!
  ---不过在我看来, 这种做法有些不道德, 等着你犯错.

  类似方法四: 正则表达式.
  string regExp  =  /^[1-9][0-9]*$/;  
     if(!regExp.test( this.txtLogin.Text))  
     {  
    alert(只能是数字!);  
    this.txtLogin.clear();  
    return ; 
     }
  类似方法五: 最没有想象力的(原始)判断方法---一个一个一个一个字符判断还需要加上个for循环和n个if:
  function isInt(a)  
     { var b = "0123456789";   
     var i;
        for  (i = 0; i <a.length; i++)  
   {     
     var c = a.charAt(i);  
     if (b.indexOf(c)  ==  -1) return false;  
   }  
   return true;  
 }

1.2、使用规则表达式来验证:
<asp:TextBox ID="UserQQ" runat="server" Columns="18" MaxLength="50" Width="130px"> </asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="UserQQ" ErrorMessage="QQ号只能为数字" validationexpression="\d+"> </asp:RegularExpressionValidator>

1.3、支持多数据类型验证的TextBox:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
namespace rungoo.WebCtrlLib
{
    /// <summary>
    /// 重写的TextBox控件
    /// Author: nowind
    /// Date: 2006-5-9
    /// Email: [email protected]
    /// QQ: 87505959
   /// Home:http://www.mofun.cc
    /// <summary>

    #region 枚举数据
    /// <summary>
    /// 验证数据类型
    /// </summary>
    public enum DataType
    {
        Never,     //不验证
        String,     //字符串
        Int,     //整数
        IntPostive,    //大于0的整数
        IntZeroPostive,   //大于等于0的整数
        Float,     //数字
        FloatPostive,   //大于0的数字
        FloatZeroPostive, //大于等于0的数字
        Url,
        Mail,
        //ChineseChars,   //汉字
        EnglishChars,   //英文
        EngNum,     //英文和数字
        EngNumUnerline,   //英文、数字和下划线
        PhoneNumber,   //电话号码
        MobileNumber,   //手机号码
        PostalCode,    //邮政编码
        Custom
    }
    #endregion

    /// Attribute DefaultProperty指定组件的默认属性,ToolboxData指定当从IDE工具中的工具箱中拖动自定义控件时为它生成的默认标记
    [DefaultProperty("AllowEmpty"), ToolboxData("<{0}:WebTextBox runat=server></{0}:WebTextBox>")]
    //类MyControl派生自WebControl
    public class WebTextBox : System.Web.UI.WebControls.TextBox
    {
        #region 子控件
        //private System.Web.UI.WebControls.TextBox txtDataInput = new TextBox();
        private System.Web.UI.WebControls.RequiredFieldValidator rfvDataInput = new RequiredFieldValidator();
        private System.Web.UI.WebControls.RegularExpressionValidator revDataInput = new RegularExpressionValidator();
        private Panel pnlFrame = new Panel();    //承载其它控件的容器Panel控件
        #endregion

        private string error = "";

        #region 控件自定义属性

        [Bindable(true)]
        [Category("自定义信息区")]
        [Browsable(true)]
        [Description("是否允许空值")]
        [DefaultValue("true")]
        public bool AllowEmpty
        {
            get { return ViewState["AllowEmpty"] == null ? true : (bool) ViewState["AllowEmpty"]; }
            set { ViewState["AllowEmpty"] = value; }
        }
        [Bindable(true)]
        [Category("自定义信息区")]
        [Browsable(true)]
        [Description("验证数据类型,默认为不验证")]
        [DefaultValue("IntPostive")]
        public DataType ValidType
        {
            get { return ViewState["ValidType"] == null ? DataType.Never : (DataType) ViewState["ValidType"]; }
            set { ViewState["ValidType"] = value; }
        }
        [Bindable(true)]
        [Browsable(true)]
        [Category("自定义信息区")]
        [Description("自定义验证错误信息")]
        [DefaultValue("")]
        public string ValidError
        {
            get { return ViewState["ValidError"] == null ? "" : (string) ViewState["ValidError"]; }
            set { ViewState["ValidError"] = value; }
        }
        [Bindable(true)]
        [Browsable(true)]
        [Category("自定义信息区")]
        [Description("自定义用于验证的正则表达式,ValidType 为 Custom 时有效")]
        [DefaultValue("")]
        public string ValidExpressionCustom
        {
            get { return ViewState["ValidExpressionCustom"] == null ? "" : (string) ViewState["ValidExpressionCustom"]; }
            set { ViewState["ValidExpressionCustom"] = value; }
        }
        [Bindable(true)]
        [Browsable(true)]
        [Category("自定义信息区")]
        [Description("错误信息提示的CSS类名")]
        [DefaultValue("")]
        public string CssError
        {
            get { return ViewState["CssError"] == null ? "" : (string) ViewState["CssError"]; }
            set { ViewState["CssError"] = value; }
        }

        #endregion

        #region 构造函数
        public WebTextBox() { }
        #endregion

        #region EnsureChildControls
        protected override void EnsureChildControls()
        {
            this.rfvDataInput.CssClass = this.CssError;
            this.rfvDataInput.ErrorMessage = "*输入不能为空";
            this.rfvDataInput.Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;
            this.rfvDataInput.EnableViewState = true;
            this.rfvDataInput.ControlToValidate = base.ID;
            this.revDataInput.CssClass = this.CssError;
            this.revDataInput.ErrorMessage = "*输入格式错误";
            this.revDataInput.Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;
            this.revDataInput.EnableViewState = true;
            this.revDataInput.ControlToValidate = base.ID;
            //将子控件添加到此自定义控件中
            this.Controls.Add(rfvDataInput);
            this.Controls.Add(revDataInput);
            this.Controls.Add(pnlFrame);
        }
        #endregion

        /// <summary>
        /// 根据设置的验证数据类型返回不同的正则表达式样
        /// </summary>
        /// <returns></returns>
        #region GetRegex
        private string GetValidRegex()
        {
            string regex = @"(\S)";
            switch (this.ValidType)
            {
            case DataType.Never:
                break;
            case DataType.Int:
                error = "*必须为整数";
                regex = @"(-)?(\d+)";
                break;
            case DataType.IntPostive:
                error = "*必须为大于0的整数";
                regex = @"([1-9]{1}\d*)";
                break;
            case DataType.IntZeroPostive:
                error = "*必须为不小于0的整数";
                regex = @"(\d+)";
                break;
            case DataType.Float:
                error = "*必须为数字";
                regex = @"(-)?(\d+)(((\.)(\d)+))?";
                break;
            case DataType.FloatPostive:
                error = "*必须为大于0的数字";
                regex = @"(\d+)(((\.)(\d)+))?";
                break;
            case DataType.FloatZeroPostive:
                error = "*必须为不小于0的数字";
                regex = @"(\d+)(((\.)(\d)+))?";
                break;
            case DataType.Url:
                error = "*URL格式错误";
                regex = @"(http://)?([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
                break;
            case DataType.Mail:
                error = "*EMail格式错误";
                regex = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
                break;
            //    case DataType.ChineseChars :
            //     error = "*包含中文字符";
            //     regex = @"[^\x00-\xff]";
            //     break;
            case DataType.EnglishChars:
                error = "*只能输入英文字符";
                regex = @"[a-zA-Z]*";
                break;
            case DataType.EngNum:
                error = "*只能输入英文字符和数字";
                regex = @"[a-zA-Z0-9]*";
                break;
            case DataType.EngNumUnerline:
                error = "*只能输入英文字符、数字和下划线";
                regex = @"[a-zA-Z0-9_]*";
                break;
            case DataType.PhoneNumber:
                error = "*电话号码格式错误";
                regex = @"(86)?(-)?(0\d{2,3})?(-)?(\d{7,8})(-)?(\d{1,5})?";
                break;
            case DataType.MobileNumber:
                error = "*手机号码格式错误";
                regex = @"(0)?(13)\d{9}";
                break;
            case DataType.PostalCode:
                error = "*邮编格式错误";
                regex = @"\d{6}";
                break;
            case DataType.Custom:
                error = "*格式错误";
                regex = this.ValidExpressionCustom;
                break;
            default:
                break;
            }
            if (this.ValidError.Trim() != "")
                error = this.ValidError;
            return regex;
        }
        #endregion

        #region 将此控件呈现给指定的输出参数
        /// <summary>
        /// 将此控件呈现给指定的输出参数。
        /// </summary>
        /// <param name="output"> 要写出到的 HTML 编写器 </param>
        protected override void Render(HtmlTextWriter output)
        {
            base.Render(output);
            output.Write("&nbsp;");
            if (!this.AllowEmpty)
            {
                this.rfvDataInput.ID = "rfv" + base.ID;
                this.rfvDataInput.ControlToValidate = base.ID;
                this.rfvDataInput.RenderControl(output);
            }
            if (this.ValidType != DataType.Never && this.ValidType != DataType.String)
            {
                this.revDataInput.ID = "rev" + base.ID;
                this.revDataInput.ControlToValidate = base.ID;
                this.revDataInput.ValidationExpression = this.GetValidRegex();
                this.revDataInput.ErrorMessage = error;
                this.revDataInput.RenderControl(output);
            }
        }
        #endregion

    }
}

(转自:http://www.cnblogs.com/chenbg2001/archive/2009/05/22/1486968.html)

你可能感兴趣的:(ASP.Net TextBox控件只允许输入数字)