Summary: Data verification is a key step in ensuring normal data capture and subsequent processing and reporting. This article describes the inherent program verification infrastructure inherent, and develops a custom validation component library for providing more efficient verification functions in this paper, which is similar to the verification control using ASP.NET.
Download WinForms03162004_sample.msi sample file.
This page
Introduction to the main function program for Windows Forms Verification and Declarative Verification Establish Design Support Memory is the most sincere compliment necessary field verification program Introduction to the BasevaliDator: Turn the Facts A Custom Verification Foundation Structure Conclusion Other Custom Verification Solutions C # and Visual Basic .NetGHIS Acknowledgment Reference
introduction
Everyone calls me as a geeks, one of my favorite films is Amazon Women on the Moon, which imitates the B-class sci-fi movie in the 1950s, the style is the same as the Kentucky Fried Movie, from several comedy Make up. Among them, a short film "two identity certificates" tells the story of Karen and Jerry (respectively played by Rosanna Arquette and Steve Guttenberg) at night. The story starts from Jerry to Karen apartment. After a few minutes of relaxing and friendly conversation, Karen suddenly asked Jerry to show two identification - a credit card, a valid driver license. Karen's appointment is checked by identification, which is the main line of this comedy. Unfortunately, Jerry did not pass identity, Karen thus rejected the date. In addition to funny, this story also has practical significance, Windows Form developers can clearly recognize that data should be verified to avoid accidents, just like the STEVE GUTTENBERG in the play. Instead, successful data verification is like a date check for Rosanna Arquette in the play, which is a quite a pleasant thing for the authors of the short drama.
Main features of Windows Forms
Simply put, verification refers to the process of ensuring data integrity and accuracy before proceeding for subsequent processing or storage. Although verification can be implemented in the data layer and business rule application layer, it should be included in the representation layer to form the frontier verification defense. Using the UI, developers can usually construct a verification process that is more human, higher and providing more information, while avoiding unnecessary two-way network communication similar to crossing N-layer applications. The problem. Verify that the type, range, and business rules are checked, and the form in Figure 1 can apply all of these types of validation.
Figure 1. ADD New Employee Forms Required Verified
This form needs to verify the following:
• You must enter "Name", "Birth Date" and "Phone Number" • "Date" must be a valid date / time value • "Phone number" must be in accordance with the Australian phone number format: (XX) XXXX XXXX • New employee Take a age of at least 18 years old
Implement this verification requires a corresponding infrastructure, the Windows Form provides the infrastructure and directs it directly in each control. To indicate control of the control, set the properties of the control CauseesValidation to True, the default value of all controls. If the CausesValidation property of a control is set to True, when the focus switches to another CausesValidation value is also set to TRUE, the validating event of the previous control will be raised. Subsequently, Validating should be processed to implement verification logic, such as ensuring "Name".
Void TXTNAME_VALIDATING (Object Sender, Canceleventargs E) {
/ / Request to enter your name
IF (txtName.Text.trim () == "") {
e.cancel = true;
Return;
}
}
Validating provides a CanceleventArgs parameter that indicates whether the field is valid by setting the Cancel property of this parameter. If Cancel is True, the focus will stay on the invalid control. If set to the default value false, a validated event will be triggered, and the focus will switch to the new control. Figure 2 demonstrates this process.
Figure 2. Windows Form Verification Process
What you have to do is to inform users of the validity of your input data in a visual manner, tell us that this feature is appropriate to use the status bar. From a visual point of view, there are two problems in this technology:
1. The status bar can only display an error, and a form may contain multiple invalid controls. 2. Since the status bar is usually located at the bottom of the form, it is difficult to determine which control is for error messages.
It is confirmed that an ERRORPROVIDER component is a more excellent mechanism in terms of an error notification for one or more controls. The component combination uses the icon and tool prompt to make an error notification to the user, and display the corresponding message next to the relevant control, as shown in FIG.
Figure 3. ErrorProvider demonstration
Enabling this component is simple, just drag the ErrorProvider component to a form and configure its icon, flashing rate, and flashing style, then merge ErrorProvider to verify code:
Void TXTNAME_VALIDATING (Object Sender, Canceleventargs E) {
/ / Need to enter your name
IF (txtName.Text.trim () == "") {
ErrorProvider.seterror (TXTName "Name is Required");
e.cancel = true;
Return;
}
// Name is effective
ERRORPROVIDER.SETERROR (TXTNAME, "");
}
CauseesValidation, Validating and ErrorProvider provide an infrastructure that implements control validation, which can be repeated for other controls, such as TXTDateOfbirth and TxtPhoneNumber:
Void TxtDateOfbirth_validating (Object Sender, Canceleventargs E) {
Datetime dob;
// Need to enter DOB, and DOB must be a valid date
IF (! datetime.tryparse (txtdateofbirth.text, out dob) {
ErrorProvider.seeterror (TXTDATEOFBIRTH, "Must Be a Date / Time Value);
e.cancel = true;
Return;
}
// age is at least 18 years old
IF (Dob> DateTime.now.addyears (-18)) {
ERRORPROVIDER.SETERROR (TXTDATEOFBIRTH, "Must BE 18 or Older");
e.cancel = true;
Return;
}
// DOB is valid
ErrorProvider.seeterror (txtdateofbirth, "");
Void TxtPhoneNumber_Validating (Object Sender, Canceleventargs E) {
// Need to enter a phone number, and the format must meet the Australian phone number format.
Regex RE = New Regex (@ "^ / (/ D {2} /) / d {4} / d {4} $");
IF (! RE.ISMatch (txtphonenumber.text) {
ERRORPROVIDER.SETERROR (TXTPHONENUMBER, "Must BE (XX) XXXX XXXX");
e.cancel = true;
Return;
}
// Phone number is valid
ERRORPROVIDER.SETERROR (TXTPHONENUMBER, "");
}
Form range verification
The combination of Validating events and ErrorProvider components provides an excellent solution that dynamically verifies each control when needed (ie when the user enters data). Unfortunately, the dependence on Validating events makes the solution automatically extend to support the form range (this verification is required when the user clicks the OK button is completed. Before you click the OK button, one or more controls may not be focus, so it does not cause its validating event. Form-range verification is implemented by manually calling the authentication logic in each Validating event, the method is to enumerate all controls in the form, set the focus for each control, then call the Validate method of the form, as follows Show:
Void BTNOK_CLICK (Object Sender, System.Eventargs E) {
Foreach (Control Control IN Controls) {
// Set the focus on the control
Control.focus ();
// Verify that the verification event caused by the initiation control,
// If CausesValidation is TRUE
IF (! Validate ()) {
DialogResult = DialogResult.none;
Return;
}
}
}
The CANCEL button does not need to implement a form of validation because it is only used to close the form. If the user is currently inactive, the user will not be able to click the Cancel button because the Cancel button's CausesValidation property is also set to True by default, so the focus is retained. Set the Cancel button's CausesValidation to false, you can easily avoid this, thereby causing Validating in a control that has been transferred from middle, as shown in Figure 4.
Figure 4. Block verification
The Add New Employee form contains approximately 60 lines of code that supports basic verification.
Program verification and declarative verification
From the perspective of work efficiency, there is a fundamental problem that a large application typically contains multiple forms, and each form is usually more controlled than the small program example of this article, so there is more Verification code. More and more code written in UI is increasingly complex, therefore should be avoided as much as possible. One of the solutions is to identify the general authentication logic and package it to the reusable type. This helps reduce client code for creating and configuring the required validation object instance. However, despite the step toward the right direction, the solution still needs to write program code. But it provides a Windows Form UI General Mode - representing the type of Windows Form to perform most tasks (most client code is used to configure these types of properties, which is ideal for Windows Forms or controls The option. Package the code in this way, the developer's work is converted to drag and drop the component or control from the Toolbox to the form, configure it from the design function (such as "Property Browser", then letting the Windows window The body designer is implemented to convert the design time to the workload of the code in InitializeComponent. This, the programming work is converted to declarative work, where declarative is a synonym of high efficiency. This is a Windows Form Verification It is an ideal situation. Establish design support
The first step is to establish design-time support, which requires one of the three types of design-time components: system.componentmodel.component, system.windows.forms.userControl. If the logic does not require a UI, Component is the correct choice; otherwise, Control or UserControl is the correct choice. The difference between Control and UserControl is the way UI's rendering. The former is presented by the custom drawing code you have written, and the latter is rendered by other controls and components. The existing verification code does not perform its own drawn because it passes the task to ErrorProvider. Therefore, Component has become the best choice for packaging verification.
Imitation is the most sincere compliment
The next step is to clarify the required verification program type. First, you should learn about the authentication program implemented by the ASP.NET. Why is this this? I am a faithful attraction of consistency, and in my forehead, there is a word "don't have more this" (of course, I can see it in the mirror when brushing the teeth). Therefore, I think the primary goal is to create a Windows Form Verifier that holds the WINDOWS Forms (if the solution applies to Windows Forms) in public types and members of the ASP.NET. In addition to their tribute to the ASP.NET team, this option can also enhance the understanding of developers using different development models. ASP.NET currently provides the verification program listed in the following table.
Verify Control Description RequiredFieldValidator Make sure the field contains Value RegularExpressionValidator CompareValidator to the Target Field and Other Fields or Values Use the Regular Expression Verification Field to equiptribly Test the RangeValidator test field belongs to some special type and / or in the specified range CustomValidator is complex Custom authentication logic for other verification program processing capabilities Create a server-side event handler
In addition, I think that another goal is to be scalable so that when the provided verification program does not meet the requirements, the developer can enter their own custom verification programs into the infrastructure when they need a small amount of work. Finally, in order to reduce the workload, realization should take advantage of our previously discussed Windows Form Verification infrastructure.
Required Field Verification Program
After the above goals are made, now we have begun to understand the specific operation details. First, we will create a simplest verification program, which is RequiredFieldValidator. Visual Studio .NET Solution
We will need a Visual Studio® .NET solution to implement RequiredFieldValidator. When generating a component or control library, I tend to adopt the "two project" methods to split the solution into a component or control project and a corresponding test tool project, the method is:
1. Create a solution (winforms03162004_CustomValidation) 2. Add a Windows Forms Application project to the solution in CustomValidationSample 3. Add a Windows Forms Control project to the solution CustomValidation 4. Delete the default UserControl1 5. Add a name from CustomValidation project For the new class of the RequiredFieldValidator, and derive from system.componentmodel.component
Note Because these verification components are not limited to WHIDBEY, I use Visual Studio .NET 2003 and .NET Framework 1.1.
interface
Maintain consistency requirements The implementation of the same applies to the interface of the Windows Form. This means that the same member is implemented by ASP.NET RequiredFieldValidator:
Class RequiredFieldValidator: Component {
String ControlTovAlidate {Get; set;}
String ErrorMessage {Get; set;}
String InitialValue {Get; set;}
Bool isvalid {get; set;}
void validate ();
}
Each member is described in detail below.
Members Description ControlTovAlidate Specifies the control to verify. ErrorMessage When the message is displayed when ControlTovAlidate is invalid. The default is "" ". InitialValue enforce value does not necessarily mean "" "" " In some cases, the default control value may be used to prompt, such as "[choose a value]" in the ListBox control. In this case, the required value must be different from the initial value "[choose a value]".. InitialValue supports this request. The default is "" "". After isvalid calls Validate, report whether the ControlToValidate's data is valid. As with the ASP.NET implementation, when you need to override Validate, you can set IsValid from the client code. The default is TRUE. Validate verifies the ControlTovAlidate's value and stores the results in IsValid.
In ASP.NET, ControlTovAlidate is a string for the server-side control instance, a string that is indexed in the process of processing a web application, requiring this indirect approach. This control can be directly referenced because there is no need to do the same consideration in a Windows form. In addition, since ErrorProvider will be internally used, we will add an ICON property to develop by developers. After the above requirements, the interface needs to be adjusted as follows:
Class RequiredFieldValidator: Component {
...
Control ControlTovAlidate {Get; set;}
Icon icon {get; set;}
...
}
achieve
The following is the ultimate implementation:
Class RequiredFieldValidator: Component {
// Special field
...
Control ControlToValidate
Get {return_controltovalidate;
SET {
_ControlTovAlidate = Value;
// Operation (ie, from vs.net) to associate ControlTovAlidate
// Validating event
IF ((_ControlTovalidate! = null) && (! designmode)) {
_ControlTovAlidate.validating =
New CanceleventHandler (ControlToValidate_Validating);
}
}
}
String errorMessage {
Get {return_errorMessage;}
Set {_ERRORMESSAGE = VALUE;
}
Icon icon {
Get {return _icon;}
Set {_ICON = Value;
}
String InitialValue {
Get {return _Initialvalue;
Set {_Initialvalue = value;
}
Bool isvalid {
Get {returnd_isvalid;}
Set {_isvalid = value;}
}
Void validate () {
// If the initial value (this value is not an empty string),
// is effective
String controlValue = controltovalidate.text.trim ();
String InitialValue;
IF (_IntialValue == null) InitialValue = ""
Else InitialValue = _InitialValue.trim ();
_ISVALID = (ControlValue! = INITIALVALUE);
// If ControlTovAlidate is invalid, an error message is displayed.
String ErrorMessage = ""
IF (! _ISVALID) {
ErrorMessage = _ERRORMESSAGE;
_ERRRPROVIDER.ICON = _ICON;
}
_ERRRPROVIDER.SETERROR (_ControlTovAlidate, ErrorMessage);
}
Private Void ControlToValidate_Validating
Object sender,
Canceleventargs e) {
// Do not cancel when it is invalid, because we don't want to be invalid
/ / Forced focus keep on ControlTovAlidate
Validate ();
}
}
The key to this implementation is how to associate it to the ValidAlIDate of ControlTovAlidate:
Control ControlTovAlidate {
Get {...}
SET {
...
// Runtime (ie when it is not in VS.NET design) associated with ControlToValidate
// Validating event
IF ((_ControlTovAlidate! = null) && (! designmode)) {_ControlTovAlidate.validating =
New CanceleventHandler (ControlToValidate_Validating);
}
}
This makes it possible to dynamically perform the desired field verification when entering data, just like a standard Windows form implementation. In addition, it has also been unevenly benefits. In the initial implementation, the focus remains in the control until the control is valid, however, until its validating event's Canceleventing event is set to false (ie, capture users in this control). Data Enter UI should not capture users anywhere, which is reflected in ControlTovAlidate_validating, which is controlled as its own authenticated trigger (rather than as a mechanism integrated with the base verification structure). Figure 5 shows an updated process.
Figure 5. Updated verification process
Integrated design
In addition to design, the functionality of this implementation is complete. All excellent Visual Studio .NET design When members use a variety of features to specify their design time behavior. For example, RequiredFieldValidator specifies the custom icon displayed in Toolbox and Component TRAY with ToolboxBitMapAttribute and uses CategoryAttribute and DescriptionAttribute to make RequiredFieldValidator's public properties more descriptive in "Properties Browser":
ToolboxBitmap
TypeOf (RequiredFieldValidator),
"RequiredFieldValidator.ico")]]]
Class RequiredFieldValidator: Component {
...
[Category ("Behaviour")]]]
[Description ("Gets or sets the control to validate.")]]
Control ControlToValidate {...}
[Category ("APPEARANCE")]]]]
[Description ("Gets or sets the text for the error message.")]]]]
String ErrorMessage {...}
[Category ("APPEARANCE")]]]]
[Description ("Gets or sets the icon to display errorMessage.")]
Icon icon {...}
[Category ("Behaviour")]]]
[Description ("Gets Or Sets The Default Value to Validate Against.")]]]]
String InitialValue {...}
}
Complete implementation of several other design functions (these features beyond the category of this article), including:
• Specify the controls that can be selected from the "Property Browser". This implementation allows TEXTBOX, ListBox, ComboBox, and UserControl Controls • Hide IsValid from "Properties Browser" because it is only runtime attributes (all public properties are automatically displayed in the Property Browser when design). To learn more about design, see the following article:
• Building Windows Forms Controls and Components with Rich Design-Time Features, Part 1 • Building Windows Forms Controls and Components with Rich Design-Time Features, Part 2
Use RequireDfieldValidator
To use RequiredFieldValidator, you should first add it to Toolbox, and then drag it to the form and configure it. To do this, the following will be performed:
1. Regenerate the solution. 2. Open the test form in Visual Studio .NET. 3. Right-click Toolbox and select Add Tab. 4. Create a tab called Custom Validation and select it. 5. Right-click Toolbox and select Add / Delete Item. 6. Browse to the newly generated component assembly (CustomValidation.dll) and select it.
The components can be used in the Windows Form Designer by the above steps, as shown in Figure 6.
Figure 6. RequiredFieldValidator presentation with runtime properties
I applied RequiredFieldValidator for all fields in the Add New Employee form, and contains a prompt for the value type that the user can enter in each field. Figure 7 shows how it works at runtime.
Figure 7. Fun time
BasevaliDator:
With RequiredFieldValidator, you can easily implement the rest of the verification program. But maybe it will not be so easy. RequiredFieldValidator will closely associate with the remaining main part of the logic of the specific "Required" authentication logic to each verification program (such as the control you want to verify). In this case, a suitable solution is to divide RequiredFieldValidator into two new types, named, and is derived and relatively simple RequiredFieldValidator. Strictly speaking, from the perspective of consistency, we should also create an IVALIDATOR interface and achieve BaseValidator by the same way as ASP.NET. However, the degree of scalability provided by this method exceeds our current needs. The basevalidator implements a reusable part of the validation logic similar to the original RequiredFieldValidator:
Abstract Class Basevalidator: Component, iValidator {
Control ControlToValidate {...}
String ErrorMessage {...}
Icon icon {...}
Bool isvalid {...}
Void validate () {...}
Private Void ControlToValidate_Validating (...) {...}
}
Although IsValid and Validate are common, they are only existing as a form in the new infrastructure, thereby remembering a specific verification to each derived verification program. Therefore, BaseValidator requires a mechanism that it is valid if it can "ask" to derive the verification program. This is achieved through an additional abstract method EVALUATESVALID. EvaluateISvalid and Basevalidator are abstract to make sure that each derived verification program knows that they can answer this question. The new addition section requires some reconstruction, as shown below: Abstract Class BasevaliDator: Component {
...
Void validate () {
...
_ISVALID = evataSvaliD ();
...
}
Protected Abstract Bool EvaluateISvalid ();
}
The result is that basevaliDator can only be used by derived methods, so EvaluateSvalid must be implemented. The Validate method has been updated and can be called down to query if it is valid. The technology is also applied to the ASP.NET control, thereby enhancing the required consistency.
RequiredFieldValidator: Redux
After completing the basevalidator, we need to refactor the RequiredFieldValidator to achieve its own functionality, which is derived from BaseValidator and implements the specified field verification bit in EvaluateISvalid and InitialValue. Based on the principle of simple, the following is the simplest new RequiredFieldValidator:
ToolboxBitmap
TypeOf (RequiredFieldValidator),
"RequiredFieldValidator.ico")]]]
Class RequiredFieldValidator: basevalidator {
String InitialValue {...}
Protected Override Bool EvaluateISvalid () {
String controlValue = controltovalidate.text.trim ();
String InitialValue;
IF (_IntialValue == null) InitialValue = ""
Else InitialValue = _InitialValue.trim ();
Return (ControlValue! = InitialValue);
}
}
A place of stay, a pound
Reasonably dividing the normal verification function and a specific verification function between the base class and the derived class enables us to focus only on a specific verification. This is not only applicable to RequiredFieldValidator, but also for the rest of the verification programs that should be consistent with ASP.NET, these verification programs include:
• RegularExpressionValidator • CustomValidator • CompareValidator • RangevaliDator
Let us know each verification program and logic used to implement them.
RegularExpressionValidator
Regular expression is a powerful text mode matching technology based on a large number of tokens. When the field requires a particular form of value, the regular expression is an excellent string operation alternative method, especially for important text modes. For example, make sure the phone number meets the Australian format ((xx) xxxx xxxx) can be simplified as a regular expression: ^ / (/ d {2} /) / d {4} / d {4} $
The advantage is why ASP.NET implements regularExpressionValidator, and we will also implement:
Using system.text.regularExpressions;
...
ToolboxBitmap
TypeOf (RegularExpressionValidator),
"RegularExpressionValidator.ico"]]]
Class RegularExpressionValidator: Basevalidator {
...
String validationExpression {...}
Protected Override Bool EvaluateISvalid () {
// If it is empty, it is not verified.
IF (ControlToValidate.Text.trim () == "") Return True;
// If you match the entire text of ControlTovAlidate,
String Field = ControlToValidate.Text.trim ();
Return Regex.ismatch (Field, _ValidationExpression.trim ());
}
}
In design, developers can provide authentication expressions through the property browser, as shown in Figure 8.
Figure 8. Regular expression specified by the verification
CustomValidator
Sometimes, specific verification procedures cannot solve specific validation issues, especially when complex business rules are required to access database access. In this case, custom code can be written, and CustomValidator enables us to write this custom code and make sure it is integrated with the custom verification infrastructure, which is important for the verification of future formal ranges. CustomValidator contains Validating events and ValidatingCanceEventArgs to meet this request:
[Toolboxbitmap (TypeOf (CustomValidator), "CustomValidator.ico"]]]
Class CustomValidator: Basevalidator {
Class ValidatingCanceEventEventArgs {...}
Delegate Void ValidatingEventHndLer (Object Sender, ValidatingCanceEventArgs E);
Event validatingeventhandler validating;
Void OnValidating (ValidatingCanceEventArgs E) {
IF (Validating! = NULL) Validating (this, e);
}
Protected Override Bool EvaluateISvalid () {
// Pass the verification process to the event handler and wait for a response
ValidatingCanceEventArgs args =
New ValidatingCanceEventEventArgs (False, ControlTovAlidate);
OnValidating (ARGS);
Return args.valid;
}
}
To process the Validating event of CustomValidator, double-click the event in the Properties Browser, as shown in Figure 9: Figure 9. Creating a verification handler for custom complex verification
Then, simply add the corresponding verification logic, the verification logic in the following example ensures that new employees are greater or equal to 18 years old:
Class AddNewemPloyeeform: Form
Void cstmdob_validating (Object Sender, ValidatingCanceleventArgs E) {
Try {
/ / Must be greater than or equal to 18 years old
DateTime Dob = DATETIME.PARSE ((Control) E.CONTROLTOVALIDATE .TEXT);
DateTime legal = datetime.now.addyears (-18);
E.valid = (DOB } Catch (Exception EX) {E.VALID = FALSE; } Note that CustomValidator is naming its equivalent event serverValidate based on the ASP.NET server-side processing feature. We use validating because we don't need to do this, and basevalidator has used Validate to derived Validate. BaseCompareValidator This verification program can only process a field. However, in some cases, verification may involve multiple fields and / or values, whether to ensure that the value of a field is in the maximum / minimum range (COMPAREVALIDATOR). In any case, additional work is required to perform type inspection, conversion, and comparison, including the type of reference to the verification. This feature is encapsulated in the new type BaseCompareValidator, from which RangeValidator and CompareValidator can save some additional work. BaseCompareValidator is sent from BaseValidator to get basic validation support and implement four new members: Abstract Class BaseCompareValidator: basevalidator { ... ValidationDataType Type {...} protected typeconverter typeconverter {...} Protected Bool CANCONVERT (STRING VALUE) {...} protected string format (string value) {...} } ValidationDataType is a custom enumeration that specifies the type of support for comparison and range authentication: ENUM VALIDATIONDATATYPE { Currency, Date, Double, Integer, String } Rangevalidator RangeValidator can be used if you need to determine if a field value is within the specified range. It allows developers to enter minimum and maximum values and the types suitable for all correlation values. In the following example, RangeValidator is derived from BaseCompareValidator: [ToolboxBitmap (Typevalidator), "RangeValidator.ico"]] Class Rangevalidator: BaseComparevalidator { ... String minimumvalue {...} String MaximumValue {...} protected override bool evaluateisvalid () { // If it is empty, it is not verified, unless the verification is required. // Verify and convert the maximum value // Verify and convert the maximum value / / Check if the minimum value <= maximum // Check and convert ControlToValue / / Whether minimum value <= value <= maximum value } } "Properties Browser" is used to configure scope and type properties, as shown in Figure 10. Figure 10. Configuring RangeValidator CompareValidator The last introduction is CompareValidator (putting it in the last introduction does not mean its importance), and CompareValidator is used to perform equality testing for ControlToValidate and other controls or values. The equivalence test of the control or value is specified by ControlToCompare or ValuetoCompare: [ToolboxbitMap (TypeF (CompareValidator), "CompareValidator.ico"]] Class CompareValidator: BaseComparevalidator { ... Control ControlToCompare {...} ValidationCompareOperator Operator {...} String Valuetocompare {...} Protected Override Bool EvaluateISvalid () { // If it is empty, it is not verified, unless the verification is required. // Check the ControlToCompare // Check the valuetocompare // Verify and convert CompareFrom // Verify and convert COMPARETO // Perform comparison, such as ==,>,> =, <, <=,! = } } Operator defines equality tests performed in ControlTovAlidate and ControlToCompare or ValuetOcompare. Operator specifies by ValidationCompareOperator: ENUM VALIDATIONCOMPAROPERATOR { DataTypecheck, Equal, Greaterthan, Greaterthanequal, Lessthan, Lessthanequal, Notequal } As you know, you can also use CompareValidator to verify that the control channelovalidate is a special data type (specified by the DataTypeCheck value). This is the only one that does not need to be a comparison of ValuetOcompare if you need ControlToCompare. Figure 11 shows how to configure COMPAREVALIDATOR. Figure 11. Configuring CompareValidator Completed custom verification infrastructure At this point, all authentication program components equivalent to the ASP.NET have been listed and explained. Each implementation is directly or indirectly derived from BaseValidator to inherit basic, reusable verification. Such inheritage creates an implicitly extended infrastructure, other developers can use this infrastructure as we are in this article. Figure 12 shows the custom verification solution and developers who can use it in situations. The case where the custom verification solution must be used, including: • Create a new normal verification program • Create a business rule-specific authentication program • Add additional relevant logic to an existing verification program Figure 12 shows the scalable support provided by this design. Figure 12. Debamable support conclusions of custom verification First, we introduced the verification framework in the Windows Forms built into the .NET Framework. We then reapperse the verification logic to multiple design time to convert the initial program verification process to a more declarative, and more efficient process. In this process, we create an extensible verification infrastructure based on BasevaliDator to implement RequiredFieldValidator, RegularExpressionValidator, CustomValidator, CompareValidator, and RangeValidator. This design allows other developers to easily create new authentication programs, and the method is also derived from BaseValidator to inherit normal features and reduces the range of implementation to specific validation. This paper mainly introduces the validation of the control, and only provides an explanation only for the formal validation of the form. The next article will be incorporated on the Form-range verification based on custom verification, describe how to combine existing verification programs and add another main part of the ASP.NET verification control collection, that is, the Validationsummary control. Now, I suggest you take a look at Amazon Women on The Moon, just find some laughter. Other custom verification solutions I originally created a verification component for GENGHIS to be traced back to the second half of 2002. In the MSDN Magazine in the Institute, I found that Billy Hollis provided by the VAT segment provided in his (and Rocky) MSDN Online column, which is an Adventures In Visual Basic .NET. It is highly recommended that you read this article and create an excellent Windows Form Verification Solution to replace the one I created. This article also introduces how to extend the expansion attribute issues when designing. C # with Visual Basic .NET The two articles I wrote in front emphasized that the code snippet prepared in the article applies only to C #, and many readers in the column are Visual Basic® .NET developers. I am in love with C #, but it is also very happy to write programs for Visual Basic.net. I originally hoped to provide a code instance of Visual Basic .NET and C #, but due to time, the two failed to be combined together and written into their own columns. But I don't want to rule out any of the two, as a compromise, I will convert between Visual Basic .NET and C # code in every article. This will make the first program fragment for Visual Basic .NET in two articles (the next authentication clip will continue from the C # work starting at this). During this work, it is happy to maintain communication with the two codes. Does the solution meet the needs? Please send me an email and tell me your thoughts. Genghis A slightly different solutions to this solution are currently available in GENGHIS. Genghis is a shared source code collection serving the .NET Windows Forms developers on Microsoft Foundation Classes (MFC). Interestingly, I am writing this article, some places need to be improved, but these improvements will be reflected in the next version of Genghis. However, if you can't wait, you can download this article at any time. If you have time, please send me a mistake or hope to improve. Thank you This article was inspired by Ron Green, Chris Sells and Amazon Women on the Moon. Reference • Validator Controls for Windows Forms in Billy Hollis For details on how to develop in-depth introductions for design-oriented components and controls, see: • Michael Weinhardt and Chris Sells book Building Windows Forms Controls and Components with Rich Design-Time Features, Part 1, MSDN Magazine, April 2003 • Michael Weinhardt and Chris Sells book Building Windows Forms Controls and Components with Rich Design -Time Features, Part 2, MSDN Magazine, May 2003 If you are not familiar with the regular expression, please refer to the following information: • Jeffery E. F. FRIEDL, O'Reilly Mastering Regular Expressions, Second Edition, 2003 • Michael Weinhardt and Chris Sells Regular Expressions In .NET, Windows Developer Magazine, December 2002 Michael Weinhardt is currently engaged in full-time .NET program writing work, including writing Windows Forms Programming IN C #, 2nd Edition (Addison Wesley), and writing this column with Chris Sells. All in all, Michael is obsessed with .NET, especially Windows forms, and see 80 episodes of TV series when possible. For more information, please visit http://www.mikedub.net/.