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