Introduction to validation controls for ASP. NET Advanced Programming basics

Source: Internet
Author: User
Tags comparison regular expression zip

Directory
1. Verification control Overview
2. Verify the usage of the control
3. Summary

--------------------------------------------------------------------------------

1. Verification control Overview
As the name suggests, a verification control is a control that verifies the correctness of user input data. If a user enters data in the text box, a prompt is displayed, indicating that the verification data is invalid. The verification process can be executed on both the server and the client. The verification code run on the client is executed before the data is submitted. Therefore, the program performance can be improved. The validation controls of ASP. NET can be used for various verifications, such as data range checks, comparison between data, and custom verifications. The following sections describe these verification controls one by one.


Differences between the three controls
(1) HTML controls. ASP. NET renders HTML controls to the browser as common strings without checking for correctness and cannot process them on the server.

(2) ASP. NET server control, after ASP. NET highly encapsulated controls are easy to use and run on the server side. You can use the C # code on the server side to perform operations and render them to the client as HTML controls.

(3) for the HTML control of runat = "server", add runat = "server" on the basis of the HTML control, which is also running on the server. Alternatively, the server can use C # for operations, it will also be rendered to the client, unlike ASP. NET Server controls are highly encapsulated, and the exposed attributes are mostly common HTML attributes, and ASP. NET server control compared to the following advantages: when you need to operate the control on the server, if the control is not ASP. when the control on the NET server is encapsulated, it is more convenient to use the HTML control of runat = "server". The HTML control of runat = "server" also processes the virtual path, id-> ClientID, therefore, you may also use the virtual path and UserControl.

<Input type = "Text" id = "txt1" runat = "server"/>

(4) a-> HtmlAnchor; form-> HtmlForm; head-> HtmlHead; input-> HtmlInputButton, HtmlInputCheckBox, HtmlInputText, etc.; meta-> HtmlMeta; table-> HtmlTable; tr-> HtmlTableRow; td-> HtmlTableCell; title-> HtmlTitl. The type of the label (for example, div) encapsulated separately is HtmlGenericControl. Use the Attributes attribute to operate unencapsulated Attributes.

(5) server-side HTML controls are not like ASP. NET controls, such as ASP. the BgColor attribute of the NET control is of the Color type, while the BgColor attribute of the HTML control is of the string type. Developers need to set the appropriate value.

Note: write the following code in ascx: drag and drop a TextBox control and a Button control. If you want to operate it, assign a value to the TextBox when the mouse slides over the Button control, if onmouserover is directly written in the Button control, an error is reported. Therefore, we need to write a JavaScript method separately.

The code is as follows: Copy code

<Script type = "text/javascript">

Document. getElementById ("<% = Button1.ClientID %>"). onmouserover = function (){

Document. getElementById ("<% = TextBox1.ClientID %>"). value = "Kencery ";

    }

</Script>

Verify controls
(1) legality verification must be performed on the data entered by the user. Many of these verification logics are repeated. For example, the field cannot be blank, it must be in the date format, and the number cannot exceed 100, in addition, it is necessary to verify both the client and the server at the same time to improve the availability of client verification, server verification to prevent malicious attacks, ASP. NET verification controls are provided to simplify these issues.

(2) ASP. NET provides the following components:

1) RequiredFieldValidator: The field is required.

2) RangeValiclator: The value ranges between the given maximum and minimum values.

3) CompareValidator: used to compare whether the relationship between two values meets the requirements or whether data of the specified type is used.

4) RegularExpressionValidator: verifies that the data meets the regular expression.

5) CustomValidator: custom verification.

(3) RequiredFieldValidator

1) ControlToValidate sets the control to be verified. The Text attribute is the error message displayed when the verified control is empty. Text can not only write Text, but also write any HTML content.

2) Sometimes the control is considered as a null value if it is the default value, for example, the selected value of the drop-down list "--- select gender ---", and the value of the text box is "fill in the search keyword ", you only need to set the InitialValue attribute of RequiredFieldValidator to "--- select gender ---" and "enter the search keyword.

(4) Validator

1) the IsValid attribute in the page is used to determine whether all Validator on the page has been verified. It is True only when all vertices have been verified, even if the Validator server verification on the page reports an error (disabling JavaScript to skip client verification), the service code in the server method (such as btnOK. click) will also be executed. Therefore, if the code cannot be executed when the data verification fails, you need to determine the IsValid value.

Note: write the following code under the Button control:

The code is as follows: Copy code

If (! IsValid ){

Return;

}

If (this. IsValid)
{    
Correct information;
Else {
 
Error message;

}}

2) all verification controls have the Display attribute to determine how to Display error messages. Three values: static: when there is no error message, the Visiblity style of the control is Hidden; Dynamic, when there is no error message, the display style of the control is none to hide, the difference between the two is that the Visiblity: hidden control still occupies space, while the display: none hidden control does not occupy space, the Display attribute can also be set to None (used together with the ValidationSummary described later ).

3) almost all verification controls have the ControlToValidate and Text attributes. All controls must be verified on the client and server.

4) if both the registration and logon forms are placed on a page, their authentication will be performed at the same time. In this way, registration verification will be triggered even though only logon is performed, you can use the verification group to solve this problem. Set the ValidationGroup of controls (forms, submit buttons) in the same group to the same value, in this way, the same control as the ValidationGroup control that triggers the event such as the Button will be verified.

5) If you set the CausesValidator attribute of the Button control (Button, ImageButton, LinkButton) to false, clicking this Button does not trigger verification.

(5) RangeValidator

1) RangeValidator: MininmumValue, MaximumValue is the minimum, maximum, and Type attribute is the data Type (String, Interger, Double, Date, Currency, etc ). For example, the age and graduation date are within a reasonable range.

2) RangeValidator, CompareValidator, and RegularExpressValidator do not check non-null values. Therefore, if the field cannot be blank, you must use RequiredFieldValidator.

(6) CompareValidator

1) CompareValidator: the Type attribute is the same as that of RangeValidator, Operator, comparison Operator, optional values DataTypeCheck, Equal, GreaterThan, clerk, LessThan, LessThanEqual, NotEqual, ValueToCompare, the ControlToCompare setting is compared with another control.

2) check the data Type, without comparison of the range. ControlToValidate sets the control to be verified, Type sets the data Type to be verified, and Operator sets it to DataTypeCheck.

3) for range comparison, ControlToValidator sets the control to be verified, Type sets the data Type to be verified, Operator sets GreaterThan, and ValueToCompare sets the value to be compared, you can also set it dynamically during programming.

4) compared with the value of another space, ControlToValidate sets the control to be verified, Type sets the data Type to be verified, and Operator sets it to GreaterThan, controlToCompare is set to the verification control to be compared (the control on the right of the operator ).

(7) advanced Validator

1) RegularExpressionValidator and ValidationExpression attributes are regular expressions. Visual Editing of VS provides several built-in regular expressions. You can also write them by yourself. Example: check the Email address, ID card number, QQ number (5 to 10 digits), personal instructions must be between 10 to 50 words.

2) CustomValidator: custom verification control. You can use CustomValidator when the built-in validation control of ASP. NET cannot meet the requirements.

3) the ServerValidate event is the server validation code and reads args from the event processing function. value to obtain the Value to be verified. If the Value is valid, the args. isValid is set to True; otherwise, it is set to False. If a function name is set for ClientValidationFunction, the client will first call the specified JavaScript function for client verification. Otherwise, only server verification will be performed, the signature of the client-side verification function is: "function name (src, args)". The attribute and meaning of argsd are the same as those of the server.

(8) summarize error messages

1) when Validator is used, the error message is displayed at the place where it is placed. There are two possible problems: if the form is very large, the user cannot see all the error messages, you want to display the message in a centralized manner next to the submit button. If there are many error messages, the error messages will be scattered across regions, and you want to display them in a centralized manner.

2) the ValidationSummary control is used to display error information in a centralized manner. Each verification control has two attributes: ErrorMessage and Text. ErrorMessage is used to display the value in ValidationSummary and Text is used to display the value at the Validator position, if the Text field is blank, ErrorMessage will display the ValidationSummary and control positions at the same time. Generally, the Text value must be short (for example, "required ","*"), because it is directly displayed to the space location, you can know which control it refers to. ErrorMessage should be detailed (for example, "the user name cannot be blank" or "cannot be blank ), in this way, values can be read from each error message of ValidationSummary.

3) attribute of ValidationSummary: DisPlayMode: Display mode. The ShowMessageBox user also displays the warning dialog box.


Verify the usage of the control
① RequiredFieldValidator control
When the control on the page requires that data be input, RequiredFieldValidator takes effect. Select the control to be verified for the ControlToValidate attribute, and the ErrorMessage attribute indicates the error message displayed after the verification is invalid.

The code is as follows: Copy code
<HTML>
<HEAD>
<Title> RequiredFieldValidator Example </title>
</HEAD>
<BODY>
<Form id = "Form1" runat = "server">
Name:
<Asp: TextBox id = "TextBox1" runat = "server"> </asp: TextBox>
<Asp: RequiredFieldValidator id = "RequiredFieldValidator1" runat = "server"
ErrorMessage = "Please enter your name" ControlToValidate = "TextBox1"> </asp: RequiredFieldValidator>
<Asp: Button id = "Button1" runat = "server" Text = "Button"> </asp: Button>
</Form>
</BODY>
</HTML>

② CompareValidator control
The CompareValidator control is used to compare data consistency between two input controls. It can also be used to verify the data types of the control content, such as integer and string types. The ControlToCompare and ControlToValidate attributes are used to set the two controls for comparison.

The code is as follows: Copy code
<HTML>
<HEAD>
<Title> CompareValidator Example </title>
</HEAD>
<BODY>
<Form id = "Form1" runat = "server">
<P> Password:
<Asp: TextBox id = "txtPwd" runat = "server" TextMode = "Password"> </asp: TextBox> <BR>
Confirm:
<Asp: TextBox id = "TxtCfm" runat = "server" TextMode = "Password"> </asp: TextBox> </P>
<P>
<Asp: Button id = "Button2" runat = "server" Text = "Button"> </asp: Button>
<Asp: CompareValidator id = "CompareValidator1" runat = "server" ErrorMessage = "Password Error! "
ControlToValidate = "TxtCfm" ControlToCompare = "txtPwd"> </asp: CompareValidator> </P>
</Form>
</BODY>
</HTML>

③ RangeValidator control
The RangeValidator control can be used to determine whether user input values are within a specific range. The attributes MaximumValue and MinimumValue are used to set the maximum and minimum values of the range.

The code is as follows: Copy code
<HTML>
<HEAD>
<Title> RangeValidator Example </title>
</HEAD>
<BODY>
<Form id = "Form1" runat = "server">
<P> Age:
<Asp: TextBox id = "TxtAge" runat = "server"> </asp: TextBox>
<Asp: RangeValidator id = "RangeValidator1" runat = "server" ControlToValidate = "TxtAge"
ErrorMessage = "Age Error! "MaximumValue =" 99 "MinimumValue =" 1 "> </asp: RangeValidator> </P>
</Form>
</BODY>
</HTML>

④ RegularExpressionValidator control
The RegularExpressionValidator control can determine whether the expression entered by the user is correct, such as the phone number, zip code, URL, etc. Select the control to be verified for the ControlToValidate attribute, and write the expression style to be verified for the ValidationExpression attribute, the example below is a piece of code for verifying the zip code.

The code is as follows: Copy code
<HTML>
<HEAD>
<Title> RegularExpressionValidator Example </title>
</HEAD>
<BODY>
<Form id = "Form1" runat = "server">
<P> Postal Code:
<Asp: TextBox id = "TxtPostalCode" runat = "server"> </asp: TextBox>
<Asp: RegularExpressionValidator id = "RegularExpressionValidator1" runat = "server"
ControlToValidate = "TxtPostalCode" ErrorMessage = "Postal Code Error! "
ValidationExpression = "d6}"> </asp: RegularExpressionValidator> </P>
</Form>
</BODY>
</HTML>

⑤ CustomValidator control
The CustomValidator control is used to perform user-defined verification. This verification can be performed on both the server side and the client side. The following code is an example of using the client to verify the zip code.

The code is as follows: Copy code
<HTML>
<HEAD>
<Title> CustomValidator Example </title>
</HEAD>
<BODY>
<Form id = "Form1" runat = "server">
<P> Postal Code:
<Asp: TextBox id = "TextBox1" runat = "server"> </asp: TextBox>
<Asp: CustomValidator id = "CustomValidator1" runat = "server" ControlToValidate = "TextBox1"
ErrorMessage = "CustomValidator" ClientValidationFunction = "ClientValidate">
</Asp: CustomValidator> </P>
</Form>
</BODY>
</HTML>
<Script language = "vbscript">
Sub ClientValidate (source, arguments)
If isnumeric (arguments. Value) and len (arguments. Value) = 6 Then
Arguments. IsValid = true
Else
Arguments. IsValid = false
End If
End Sub
</Script>

⑥ ValidationSummary control
This control outputs all verification errors on the page as a list. The display mode of the list is set by the DisplayMode attribute.

The code is as follows: Copy code
<HTML>
<HEAD>
<Title> ValidationSummary Example </title>
</HEAD>
<Body>
<Form id = "Form1" runat = "server">
<P> Age:
<Asp: TextBox id = "TxtAge" runat = "server"> </asp: TextBox>
<Asp: RequiredFieldValidator id = "RequiredFieldValidator1" runat = "server"
ControlToValidate = "TxtAge" ErrorMessage = "Age Error! "Display =" None "> </asp: RequiredFieldValidator> <BR>
Postal Code:
<Asp: TextBox id = "TxtPostalCode" runat = "server"> </asp: TextBox>
<Asp: RequiredFieldValidator id = "RequiredFieldValidator2" runat = "server"
ControlToValidate = "TxtPostalCode" ErrorMessage = "Postal Code Error! "
Display = "None"> </asp: RequiredFieldValidator> </P>
<P>
<Asp: Button id = "Button1" runat = "server" Text = "Button"> </asp: Button> </P>
<P>
<Asp: ValidationSummary id = "ValidationSummary1" runat = "server"
HeaderText = "You must enter a value in the following fields:"> </asp: ValidationSummary> </P>
</Form>
</Body>
</HTML>
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.