Asp.net| Server | control | example in
Previous Article, we explained some of the knowledge about implementing validation controls. The content will provide a foundation for developers to implement validation controls. To help readers better understand how validation controls are implemented, this article first describes the implementation steps for common validation controls, and then demonstrates how to validate the controls by using a typical example.
1. Validation control Implementation Steps
In the process of creating validation controls, you need to implement core content such as server-side validation and client validation. The following are examples of common implementation steps for validation controls.
(1) The validation control class should be inherited by the BaseValidator base class. This allows validation controls to automatically inherit the functionality required to participate in the validation framework. For example, by inheriting the BaseValidator ControlToValidate property, you implement the association of the validation control with the validation target control.
(2) Implement some properties that are specific to the validation control. Developers can define these unique properties from a convenient and practical perspective, based on application requirements.
(3) Rewrite the AddAttributesToRender method to add unique properties and related content to the control rendering. When implementing client-side validation code, you may need to refer to related rendering content.
(4) Rewrite the EvaluateIsValid method to add server-side validation logic to the validation control.
(5) Rewrite the event handling method for the PreRender event OnPreRender, in addition to invoking the base class implementation method, to implement the registration of client-side validation script files.
(6) Write a client-side validation script file packaged with the validation control and place it in the correct directory.
With one or more of these steps, the developer can implement a basic validation control. In the implementation process, the server-side validation logic and the client verification logic must be consistent, otherwise, even if the input data is validated by the client, it cannot be validated through the server side. The following is a typical example to further illustrate how validation controls are implemented to deepen the reader's understanding.
2. Typical application
In this section, you create a validation control named Telnumvalidator, using the method of developing the validation control described earlier. The control is used to verify that the phone number entered by the user conforms to the rule. If the rule is not met, then the dynamic prompts the error message. The effect is shown in Figure 1.
Figure 1 Effect chart (input error status)
As shown in Figure 1, the page mainly includes a TextBox text box and a Submit button. The user must enter a phone number in the correct format to pass validation. In Figure 1, the submit page cannot be implemented when the Submit button is clicked, because the correct phone number is not entered. At the same time, the page also dividend blue two color gives the hint information. The following is a detailed explanation of the implementation of the validation controls.
First, before implementing the Telnumvalidator control, you must further explicitly validate the condition.
For domestic telephone number, generally two kinds of mode: one is the area code is 3 digits, the telephone number is 8 bits, the other is the area code is 4 digits, the telephone number is 7 bit. Accordingly, a regular expression for validation can be drawn: "\d{3}-\d{8}|\d{4}-\d{7}". Both the server-side validation logic and the client validation logic must comply with the above validation criteria. Only input data that conforms to both modes can be validated.
The following is a list of the source code for the server-side validation of the validation control Telnumvalidator.
Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Text;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Text.RegularExpressions;
Namespace Webcontrollibrary
{
[Defaultproperty ("Text")]
[ToolBoxData ("<{0}:telnumvalidator runat=server>
</{0}:TelNumValidator> ")
]
public class Telnumvalidator:basevalidator
{
Defines a private variable, where _clientfileurl represents the JavaScript file storage directory
ValidationExpression represents regular expressions
private string _clientfileurl = "clientfiles/";
Private Const string validationexpression = @ "(\d{3}-\d{8}|\d{4}-\d{7})";
Defines the property clientfileurl to get or set the script relative path
[
Description ("Get or set Script relative path"),
DefaultValue ("clientfiles/"),
Category ("appearance")
]
public string Clientfileurl
{
Get
{return _clientfileurl;}
Set
{_clientfileurl = value;}
}
overriding AddAttributesToRender, adding special properties to validation controls Evaluationfunction and Validationexp
protected override void AddAttributesToRender (HtmlTextWriter writer)
{
Base. AddAttributesToRender (writer);
if (renderuplevel)
{
Writer. AddAttribute ("Evaluationfunction", "Telnumvalidatorevaluateisvalid", false);
Writer. AddAttribute ("Validationexp", validationexpression);
}
}
Overriding the EvaluateIsValid method, defining server-side validation logic
protected override bool EvaluateIsValid ()
String controlvalue = Getcontrolvalidationvalue (ControlToValidate);
if (Controlvalue = null)
{
return true;
}
Controlvalue = Controlvalue.trim ();
Try
{
Match m = Regex.match (Controlvalue, validationexpression);
Return (m.success && (m.index = 0) && (m.length = = controlvalue.length));
}
Catch
{
return false;
}
}
Overriding the OnPreRender method, registering client-side scripting programs
protected override void OnPreRender (EventArgs e)
{
Base. OnPreRender (e);
if (renderuplevel)
{Page.ClientScript.RegisterClientScriptBlock (typeof (Telnumvalidator),
"Clientvalidator", Getclientfileurl ("Clientvalidator.js"));
}
}
Implement the auxiliary function Getclientfileurl to get the full path to the JavaScript file
private string Getclientfileurl (String fileName)
{
String tempclient = String.Format ("<script language=\" javascript\ "src=\" {0}\ "> </script>", (Clientfileurl + fileName)) ;
return tempclient;
}
}
As you know from the above code, the implementation of the Telnumvalidator control is written in accordance with the validation control implementation steps described above. This class implements the following important logic:
(1) The validation control class Telnumvalidator class inherits from the BaseValidator base class, so the class automatically inherits the properties, methods, and events that the generic validation control should have.
(2) Defines the property clientfileurl that is used to get or set a script relative path, and the default value is "clientfiles/". This property page developer can customize the directory of client-side validation script files, which increases the flexibility of the control.
(3) Rewrite the AddAttributesToRender method to add attributes Evaluationfunction and validationexp to the control. The corresponding value of the attribute Evaluationfunction is the method name for client-side validation. Attribute validationexp The corresponding value is the regular expression used for validation, which can be used by the client-side validation script by rendering it to the client.
(4) Rewrite the EvaluateIsValid method to define server-side validation logic. (5) Rewrite the OnPreRender method to register the client script file clientvalidator.js.
The reader may have noticed that the validation control needs to implement client-side validation and that client-side validation is included in the Clientvalidator.js file. By default, the file is in the Clientfiles folder.
The source code for the client-side validation file Clientvalidator.js is listed below.
Function Telnumvalidatorevaluateisvalid (val)
{
var validationexp = Val.validationexp;
var valuetovalidate = Validatetrim (Validategetvalue (val.controltovalidate));
var rx = new RegExp (VALIDATIONEXP);
var matches = rx.exec (valuetovalidate);
return (matches!= null && valuetovalidate = = Matches[0]);
}
/* Get input data to validate the target control
function Validategetvalue (ID)
{
var control;
control = Document.all[id];
if (typeof (control.value) = = "string")
{
return control.value;
}
if (typeof (control.tagname) = = "undefined" && typeof (Control.length) = = "Number")
{
var J;
for (j=0 J; control.length; j + +)
{
var inner = control[j];
if (typeof (inner.value) = = "string" && (Inner.type!= "Radio" | | inner.status = TRUE))
{
return inner.value;
}
}
}
Else
{
return validatorgetvaluerecursive (Control);
}
Return "";
}
/* Remove Space processing * *
function Validatetrim (s)
{
var m = S.match (/^\s* (\s+ (\s+\s+) *) \s*$/);
return (M = = null)? "": m[1];
}
As you know from the code above, only one main method Telnumvalidatorevaluateisvalid is included in the Clientvalidatior.js file. This method realizes the same logic as the EvaluateIsValid method in server-side verification. At the same time, two auxiliary methods Validategetvalue and Validatetrim are included. The former is used to obtain input data for the validation target control, which is used to remove whitespace processing.
To test the current custom validation control, the Default.aspx page source code is listed below.
<%@ Page language= "C #" autoeventwireup= "true" codefile= "Default.aspx.cs" inherits= "_default"%>
<%@ Register tagprefix= "Sample" assembly= "Webcontrollibrary" namespace= "Webcontrollibrary"%>
! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title> implement a validation control </title>
<body>
<form id= "Form1" runat= "Server"
<div style= "Font-size:small;" >
<asp:textbox id= "TextBox" runat= "Server" > </asp:TextBox>
<asp:button id= "Button1" runat= "Server" text= "submit" > </asp:Button>
<sample:telnumvalidator id= "Demo1" runat= "Server" display= "dynamic" controltovalidate= "textbox" text= "Please enter a valid phone number" errormessage= "The correct format is 010-12345678 or 0123-1234567" > </Sample:TelNumValidator>
<BR/><BR/>
<asp:validationsummary runat= "Server" forecolor= "Blue" displaymode= "singleparagraph" error message: "Headertext=" ValidationSummary1 "> </asp:ValidationSummary>
</div>
</form>
</body>
In the above implementation, readers will focus on the property settings of the custom validation control. The control mainly sets the following important properties.
(1) The ControlToValidate property, which implements the validation control Telnumvalidator and verifies the association between the target control textbox.
(2) Display property, by setting this property, you can set the way the error message is displayed.
(3) ErrorMessage, which is used to get or set the text of the error message displayed in the ValidationSummary control when validation fails. To do this, you also set up a corresponding ValidationSummary control in your code.
(4) text, which is used to get or set the text displayed in the validation control when validation fails.
Note that all 4 of the above attributes inherit from the BaseValidator base class. Additionally, developers can modify the Clientfileurl property of a validation control if the application deployment requires it.
3. Summary
This article illustrates the implementation of validation controls through a typical example. It is believed that readers have been able to feel that if high quality validation controls are implemented, developers must have a wide range of knowledge, especially JavaScript languages. In addition, the JavaScript code involved in this article is included in the JS file. Developers can also compile the code as a resource file into a validation control's DLL file. This implementation is very useful for the deployment of controls. Interested readers can give it a try.