日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/7/14 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.Net TextBox控件只允许输入数字 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文: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" οnkeyup='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/// <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派生自WebControlpublic 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控件#endregionprivate 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 EnsureChildControlsprotected 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 GetRegexprivate 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("?");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} }

總結

以上是生活随笔為你收集整理的ASP.Net TextBox控件只允许输入数字的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。