The ASP. NET textbox control allows only numbers to be entered

Source: Internet
Author: User

Original: ASP. NET textbox control allows only numbers to be entered

1.1. In the OnKeyPress event of the ASP. NET TextBox control, you must specify the input keyboard code as a number:

<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= "> </asp:TextBox>"

Note : If you do not allow the entry of the decimal point to remove the "event.keycode==46"

Or:

<asp:textbox id= "TextBox" runat= "server" onkeyup= ' Value=value.replace (/[^d]/g, ') ' onbeforepaste= ' Clipboarddata.setdata (' Text ', Clipboarddata.getdata (' text '). Replace (/[^d]/g, ') ' Maxlength= "> </asp: Textbox>

Similar method one:

if (e.keychar!=8! Char.isdigit (E.keychar) e.keychar!= '. ') {e.handled = true;}

Similar method two:
if (E.keychar < | | E.keychar > $) (E.keychar! = 8) e.keychar!= '. ') {e.handled = true;}


Similar method Three:
if (! Char.isnumber (E.keychar)! Char.ispunctuation (E.keychar)! Char.iscontrol (E.keychar)) {e.handled = true;}

Explanation: where E. Keychar is the key of the keyboard input corresponding to the character, IsDigit function can determine whether the number is 0 to 9, CHR (8)
As the backspace key, when E. When handled is true, the program considers that the KeyPress event has been processed and the contents of the text box are not changed.
You can enter a decimal point if the text needs to enter a decimal number. And the decimal point can only be entered once
Isnumber: Specifies whether the character at the specified position in a string belongs to a numeric category
Ispunctuation: Specifies whether the character at the specified position in the string belongs to the punctuation category
Iscontrol: Specifies whether the character at the specified position in the string is a control character category
Note: Here is the restriction that other types of characters are written to the TextBox when they are entered;
That means you don't enter the correct one or you enter the numbers and I won't let you do any other work!
Overbearing, huh? Oh, if you do not like this way, there are a few of the following allow users to enter freely,
Then judge, if not an integer, I give you a warning to tell you that the input type is not correct, please re-enter!
---but in my opinion, it's a little unethical, waiting for you to make a mistake.

Similar method four: regular expression.
  

string regExp =/^[1-9][0-9]*$/;    if (!regexp.test (this.txtLogin.Text))    {alert (only numbers!)      );      This.txtLogin.clear ();  return;    }


Similar method five: the most unimaginative (primitive) Judgment method---one character at a A to judge also need to add a for loop and 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. Use regular expressions to verify:

<asp:textbox id= "USERQQ" runat= "Server" columns= "130px" > </asp:TextBox> maxlength= "width=" : RegularExpressionValidator id= "RegularExpressionValidator1" runat= "Server" controltovalidate= "USERQQ" Errormessage= "QQ number can only be digital" validationexpression= "\d+" > </asp:RegularExpressionValidator>

1.3. TextBox supporting multi-data type verification:

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>///rewritten TextBox control///Author:nowind//<summary> #region Enumeration Data//      <summary>///Validation data type///</summary> public enum DataType {never,//Do not validate String,        String Int,//Integer intpostive,//integer greater than 0 intzeropostive,//integer greater than or equal to 0 Float,//number         Floatpostive,//number greater than 0 floatzeropostive,//numeric Url greater than or equal to 0, Mail,//chinesechars,//Kanji        Englishchars,//English engnum,//English and digital engnumunerline,//English, numbers and underscores phonenumber,//Telephone number Mobilenumber,//Mobile number PostalCode,//Zip code Custom} #endregion//Attribute Defaultproper TY Specifies the default property of the component, ToolBoxData specifies the default token that is generated for a custom control when it is dragged from the Toolbox in the IDE tool [Defaultproperty ("AllowEmpty "), ToolBoxData (" <{0}:webtextbox runat=server></{0}:webtextbox> ")]//Class mycontrol derived from WebControl public class WebTextBox:System.Web.UI.WebControls.TextBox {#region child control//private System.Web.UI.WebCont Rols.        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 ();        Container that hosts other controls #endregion private string error = "" In the Panel control; #region Control custom Property [Bindable (True)] [Category (custom Info area)] [browsable (true)] [Description ("Null value allowed") ] [DefaultValue ("true")] public bool AllowEmpty {get {return viewstate["allowempty"] = = Null? true: (bool) viewstate["AllowEmpty"];        } set {viewstate["allowempty"] = value;} } [BindabLe (True)] [Category ("Custom Information area")] [Browsable (true)] [Description ("Verify data type, default is not verified")] [DefaultValue ( "Intpostive")] public DataType Validtype {get {return viewstate["validtype"] = = null? Datatype.never: (DataType) viewstate["Validtype"];        } set {viewstate["validtype"] = value;} } [Bindable (True)] [Browsable (true)] [Category ("Custom Information area")] [Description ("Custom validation error message")] [D Efaultvalue ("")] public string Validerror {get {return viewstate["validerror"] = = null? "": ( String) viewstate["Validerror"];        } set {viewstate["validerror"] = value;} } [Bindable (True)] [Browsable (true)] [Category ("Custom Information area")] [Description ("Customize the regular expression used for validation, Validtyp E is valid for Custom ")] [DefaultValue (" ")] public string Validexpressioncustom {get {return Vi ewstate["Validexpressioncustom"] = = null? "": (String) viewstate["VaLidexpressioncustom "];        } set {viewstate["validexpressioncustom"] = value;}        } [Bindable (True)] [Browsable (true)] [Category ("Custom Information area")] [Description ("CSS class name for error message hint")] [DefaultValue ("")] public string Csserror {get {return viewstate["csserror"] = = null? "": (S Tring) viewstate["Csserror"];        } set {viewstate["csserror"] = value;} #endregion #region Constructor Public WebTextBox () {} #endregion #region Ensurechildcontrol s protected override void EnsureChildControls () {This.rfvDataInput.CssClass = this.            Csserror;            This.rfvDataInput.ErrorMessage = "* Input cannot be empty";            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 = "* Input format error";            This.revDataInput.Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;            This.revDataInput.EnableViewState = true;            This.revDataInput.ControlToValidate = base.id; Adds a child control to this custom control in this.            Controls.Add (Rfvdatainput); This.            Controls.Add (Revdatainput); This.        Controls.Add (Pnlframe); } #endregion////<summary>/////////////////&L T;returns></returns> #region Getregex private String Getvalidregex () {string reg            ex = @ "(\s)"; Switch (this.            Validtype) {case DataType.Never:break;                Case DataType.Int:error = "* Must be an integer"; Regex = @ "(-)?                (\d+) ";            Break                Case DataType.IntPostive:error = "* Must be an integer greater than 0";   Regex = @ "([1-9]{1}\d*)";             Break                Case DataType.IntZeroPostive:error = "* Must be an integer not less than 0";                Regex = @ "(\d+)";            Break                Case DataType.Float:error = "* Must be a number"; Regex = @ "(-)? (\d+) (((\.)                (\d) +))? ";            Break                Case DataType.FloatPostive:error = "* Must be a number greater than 0"; Regex = @ "(\d+) ((\.)                (\d) +))? ";            Break                Case DataType.FloatZeroPostive:error = "* Must be a number not less than 0"; Regex = @ "(\d+) ((\.)                (\d) +))? ";            Break                Case DataType.Url:error = "*url format error"; Regex = @ "(HTTP//)? ([\w-]+\.)                +[\w-]+ (/[\w-./?%&=]*)? ";            Break                Case DataType.Mail:error = "*email format error"; Regex = @ "\w+ ([-+.] \w+) *@\w+ ([-.] \w+) *\.\w+ ([-.]                \w+) * ";            Break       Case Datatype.chinesechars://Error = "* contains Chinese characters";     Regex = @ "[^\x00-\xff]";            Break                Case DataType.EnglishChars:error = "* Can only enter English characters";                Regex = @ "[a-za-z]*";            Break                Case DataType.EngNum:error = "* Only English characters and numbers can be entered";                Regex = @ "[a-za-z0-9]*";            Break                Case DataType.EngNumUnerline:error = "* Can only enter English characters, numbers and underscores";                Regex = @ "[a-za-z0-9_]*";            Break                Case DataType.PhoneNumber:error = "* Phone number format error"; Regex = @ "(86)? (-)? (0\d{2,3})? (-)? (\d{7,8}) (-)?                (\d{1,5})? ";            Break                Case DataType.MobileNumber:error = "* Phone number format error"; Regex = @ "(0)?                (+) \d{9} ";            Break                Case DataType.PostalCode:error = "* Zip format error";                Regex = @ "\d{6}";            Break                Case DataType.Custom:error = "* Format error"; Regex =This.                Validexpressioncustom;            Break            Default:break; } if (this. Validerror.trim ()! = "") error = this.            Validerror;        return regex;        #endregion #region renders this control to the specified output parameter////<summary> renders this control to the specified output parameter. </summary>//<param name= "Output" > HTML writer to be written </param> protected override void R Ender (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}}

The ASP. NET textbox control allows only numbers to be entered

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.