The ASP. Net TextBox Control allows only numbers.

Source: Internet
Author: User

1.1 In the OnKeyPress event of the Asp. Net TextBox Control, specify that the Input Keyboard code must be a number:

Only numbers can be entered: onKeyUp = "if (! /^ \ D * (\ d *)? $/. Test (this. value) this. value = this. value. substr (0, this. value. length-1 )"
Prohibit replication: onpaste = "return false"

<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>

Note: If the "event. keyCode = 46" cannot be entered as the decimal point

Or: <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>

Method 1:
If (e. KeyChar! = 8! Char. IsDigit (e. KeyChar) e. KeyChar! = '.') {E. Handled = true ;}
Method 2:
If (e. KeyChar <48 | e. KeyChar> 57) (e. KeyChar! = 8) e. KeyChar! = '.') {E. Handled = true ;}
Method 3:
If (! Char. IsNumber (e. KeyChar )! Char. IsPunctuation (e. KeyChar )! Char. IsControl (e. KeyChar) {e. Handled = true ;}
Explanation: e. KeyChar is the character corresponding to the key entered by the keyboard. The IsDigit function can determine whether it is a number ranging from 0 to 9. Chr (8)
The Return key. When the value of e. Handled is True, the program considers that the KeyPress event has been processed and the content of the text box will not change.
If you want to enter a decimal point in the text, you must be able to enter the decimal point only once.
// IsNumber: Specifies whether the character at the specified position in the string belongs to the digit 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 belongs to the control character category.
Note: When inputting, other types of characters are limited to be written into TextBox;
That is to say, if you do not enter a correct number or you do not enter a number, I will not allow you to do any other work!
Domineering? Well, if you don't like this method, there are several ways to allow users to enter it at will,
Then judge. If it is not an integer, I will give you a warning to tell you that the input type is incorrect. Please enter it again!
--- But in my opinion, this kind of practice is immoral, waiting for you to make mistakes.

Method 4: Regular Expression.
String regExp =/^ [1-9] [0-9] * $ /;
If (! RegExp. test (this.txt Login. Text ))
{
Alert (only numbers !);
This.txt Login. clear ();
Return;
}
Method 5: The least imaginative (original) Judgment Method-a one-character judgment requires a for loop and n if:
Function isInt ()
{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 rule expressions for verification:
<Asp: TextBox ID = "UserQQ" runat = "server" Columns = "18" MaxLength = "50" Width = "130px"> </asp: TextBox>
<Asp: RegularExpressionValidator ID = "RegularExpressionValidator1" runat = "server" ControlToValidate = "UserQQ" ErrorMessage = "QQ number can only be a number" validationexpression = "\ d +"> </asp: regularExpressionValidator>

1.3 TextBox that supports multi-data 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>
/// Override the TextBox Control
/// Author: nowind
/// Date: 2006-5-9
// Email: hgh113@sina.com
/// QQ: 87505959
// Home: http://www.mofun.cc
/// <Summary>

# Region enumeration data
/// <Summary>
/// Verify the data type
/// </Summary>
Public enum DataType
{
Never, // not verified
String, // String
Int, // integer
IntPostive, // an integer greater than 0
IntZeroPostive, // an integer greater than or equal to 0
Float, // number
FloatPostive, // number greater than 0
FloatZeroPostive, // number greater than or equal to 0
Url,
Mail,
// ChineseChars, // Chinese Character
EnglishChars, // english
EngNum, // english and numbers
EngNumUnerline, // english, numbers, and underscores
PhoneNumber, // phone number
MobileNumber, // mobile phone number
PostalCode, // zip code
Custom
}
# Endregion

/// Attribute DefaultProperty specifies the default Attribute of the component. ToolboxData specifies the default tag generated when a custom control 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 subcontrol
// 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 (); // container Panel control that carries other controls
# Endregion

Private string error = "";

# Region control Custom Attributes

[Bindable (true)]
[Category ("custom information area")]
[Browsable (true)]
[Description ("whether to allow null values")]
[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, not verified by default")]
[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 verification error message")]
[DefaultValue ("")]
Public string ValidError
{
Get {return ViewState ["ValidError"] = null? "": (String) ViewState ["ValidError"];}
Set {ViewState ["ValidError"] = value ;}
}
[Bindable (true)]
[Browsable (true)]
[Category ("custom information area")]
[Description ("Custom Regular Expression for verification, valid when ValidType is m")]
[DefaultValue ("")]
Public string ValidExpressionCustom
{
Get {return ViewState ["ValidExpressionCustom"] = null? "": (String) ViewState ["ValidExpressionCustom"];}
Set {ViewState ["ValidExpressionCustom"] = value ;}
}
[Bindable (true)]
[Browsable (true)]
[Category ("custom information area")]
[Description ("the CSS class name prompted by the error message")]
[DefaultValue ("")]
Public string CssError
{
Get {return ViewState ["CssError"] = null? "": (String) ViewState ["CssError"];}
Set {ViewState ["CssError"] = value ;}
}

# Endregion

# Region Constructor
Public WebTextBox (){}
# Endregion

# Region EnsureChildControls
Protected override void EnsureChildControls ()
{
This. rfvDataInput. CssClass = this. CssError;
This. rfvDataInput. ErrorMessage = "* The input cannot be blank ";
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 = "* incorrect input format ";
This. revDataInput. Display = System. Web. UI. WebControls. ValidatorDisplay. Dynamic;
This. revDataInput. EnableViewState = true;
This. revDataInput. ControlToValidate = base. ID;
// Add the child control to this custom control
This. Controls. Add (rfvDataInput );
This. Controls. Add (revDataInput );
This. Controls. Add (pnlFrame );
}
# Endregion

/// <Summary>
/// Return different regular expression patterns based on the set verification data type
/// </Summary>
/// <Returns> </returns>
# Region GetRegex
Private string GetValidRegex ()
{
String regex = @ "(\ 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 = "* Incorrect EMail format ";
Regex = @ "\ w + ([-+.] \ w +) * @ \ w + ([-.] \ w + )*\. \ w + ([-.] \ w + )*";
Break;
// Case DataType. ChineseChars:
// Error = "* contains Chinese characters ";
// Regex = @ "[^ \ x00-\ xff]";
// Break;
Case DataType. EnglishChars:
Error = "* Only English characters can be entered ";
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 = "* Only English characters, numbers, and underscores can be entered ";
Regex = @ "[a-zA-Z0-9 _] *";
Break;
Case DataType. PhoneNumber:
Error = "* incorrect Phone Number Format ";
Regex = @ "(86 )? (-)? (0 \ d {2, 3 })? (-)? (\ D {7, 8 })(-)? (\ D {1, 5 })? ";
Break;
Case DataType. MobileNumber:
Error = "* incorrect Mobile Phone Number Format ";
Regex = @ "(0 )? (13) \ d {9 }";
Break;
Case DataType. PostalCode:
Error = "* incorrect zip code format ";
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 presents the control to the specified output parameter
/// <Summary>
/// Present the control to the specified output parameter.
/// </Summary>
/// <Param name = "output"> HTML writer to be written </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

}
}

Related Article

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.