To create a TextBox control with a self-validation feature

Source: Internet
Author: User
Tags format bool extend implement integer interface net trim
Create | control

Introduction

In the mighty. NET before, I have a lot of ideas, I want ASP.net Web controls built with validation, without the need to insert too many validation controls in the page so that the code is confusing! Now we will be able to use. NET to create a TextBox control that only allows you to enter integer digits, or a TextBox control that only allows you to enter currency data, and so on. Of course, you can also specifically specify whether the TextBox control is empty or within a range, and so on, in addition, when we enter the data to meet the requirements, we can return a value to make it easier for us to see if we want to intervene, even if we can let it run with different colors depending on whether the input data meets the requirements.

After some effort, I finally realized the above ideas

Implement IValidator interface

When I delve into the SDK documentation, I find that any control can have validation capabilities as long as the IValidator interface is implemented, and here is a simple example of inheriting a TextBox control:
Using System;
Using System.Web.UI.WebControls;
Using System.Web.UI;

Namespace Myvalidatingcontrols {
public class TextBox:System.Web.UI.WebControls.TextBox, IValidator {
private bool _valid = true;
private string _errormessage = "";

public bool IsValid {
get {return _valid;}
set {_valid = value;}
}

public string ErrorMessage {
get {return _errormessage;}
set {_errormessage = value;}
}

public void Validate () {
}
}
}
Of course, this program does nothing, but it fully implements the basic IValidator interface Architecture (at least it can be compiled successfully), and I use the private keyword to create two fields (field) to hold the validation status and error messages, to ensure that the validation controls can be executed, We must add our validation controls to the collection of validation controls on the page.

When I read the SDK documentation, I found that validation controls load themselves during initialization, and the Ivalidators interfaces are used primarily to register themselves, so we need to use the overriding method to recreate the OnInit and onunload events. So that we can add or remove them from the collection of validation controls on the page
protected override void OnInit (EventArgs e) {
Base. OnInit (e);
PAGE.VALIDATORS.ADD (this);
}

protected override void OnUnload (EventArgs e) {
if (Page!= null) {
Page.Validators.Remove (this);
}
Base. OnUnload (e);
}

Complete Setup

Before we implement our verification capabilities, to make the event simpler, I set up some help items because I didn't want to provide separate error messages for the validation controls separately, but instead wanted to embed them in the control to achieve the data entry we expected, so I needed to do something Make it possible for the error prompt to appear appropriately.

I'm going to add a name called the FriendlyName property that will appear in all the error messages to prompt the user for a legitimate data type, so if the control ID we call is Retailprice, we'll make the control's riendlyname the retail price
private string _friendlyname = "";

public string FriendlyName {
get {return _friendlyname;}
set {_friendlyname = value;}
}

Finally, we rewrite the IsValid event so that it can change the background color of the control when validation does not pass
public bool IsValid {
get {return _valid;}
set {
_valid = value;
if (!_valid) {
This. BackColor = color.lightcoral;
}
else {
This. BackColor = Color.White;
}
}
}

Spaces not allowed

First we need to make sure that we provide an option to decide whether to allow null values, and we need to create a property here to determine if it can be null

private bool _blankallowed = true;

public bool Allowblank {
get {return _blankallowed;}
set {_blankallowed = value;}
}

Finally, we can rewrite the validation function

public virtual void Validate () {
This. IsValid = true;

if (!this. Allowblank) {
BOOL IsBlank = (this. Text.trim () = = "");

if (IsBlank) {
This. ErrorMessage =
String.Format ("' {0} ' cannot be blank.",
This. FriendlyName);
This. IsValid = false;
}
}
}

To broaden our creativity

Now that we have created a TextBox control with built-in basic validation capabilities, we can now extend our ideas to create more interesting TextBox controls with specific validation capabilities

The following creates a TextBox control (Integertextbox) that allows only integral data to be entered, and makes the control have only the data that is allowed to be entered must be within a certain range, but we still need to consider whether to allow null values, so, as above, you need to add a property

Based on the basic TextBox control we created above, we just need to inherit the control and then overwrite the Validate function and add some new attributes

private int _minvalue = Int32.minvalue;
private int _maxvalue = Int32.MaxValue;

public int MinValue {
get {return _minvalue;}
set {
_minvalue = value;

if (_minvalue > _maxvalue) {
int swap = _minvalue;
_minvalue = _maxvalue;
_maxvalue = swap;
}
}
}

public int MaxValue {
get {return _maxvalue;}
set {
_maxvalue = value;

if (_minvalue > _maxvalue) {
int swap = _minvalue;
_minvalue = _maxvalue;
_maxvalue = swap;
}
}
}

We then extend the Validate function and compile it as a local code

public override void Validate () {
This. IsValid = true;

BOOL IsBlank = (this. Text.trim () = = "");

if (IsBlank) {
if (! Allowblank) {
This. ErrorMessage = String.Format ("' {0} '" +
"cannot be blank." FriendlyName);
This. IsValid = false;
}
} else {
try {
_value = Int32.Parse (this. Text);
if (_value < this. MinValue) {
This. ErrorMessage = String.Format ("' {0} ' cannot" +
"Be less than {1}",
This. FriendlyName, this. MinValue);
This. IsValid = false;
}

         if (_value > this. MaxValue) {
            this. ErrorMessage = String.Format ("' {0} '" +
                "cannot be more than {1}",
                this. FriendlyName, this. MinValue);
            this. IsValid = false;
        }
     } catch {
         this. ErrorMessage = String.Format ("' {0} '" +
               ' is not a valid integer. ', this. FriendlyName);
         this. IsValid = false;
     }
  }
}

public int Value {
get {return _value;}
set {
_value = value;
This. Text = _value. ToString ();
}
}

Conclusion

To write so much, now we can also create on this class, such as requirements can only be entered in accordance with a certain time format and currency format, below we give an example to show how to use the control we created

Before that we had to implement the same functionality required to write the following code:

<asp:textbox id= "number" runat= "Server"/>
<asp:requiredfieldvalidator id= "RequiredFieldValidator2"
controltovalidate= "Number"
text= "' Number ' cannot be blank." runat= "Server"/>
<asp:rangevalidator id= "Range1" controltovalidate= "number"
Minimumvalue= "0" maximumvalue= "100"
Type= "Integer" text= "The value must is from 0 to 100!"
runat= "Server"/>

And now, we just need one sentence:
Mycontrols:integertext id= "Number"
Friendlyname= "number" minvalue= "0" maxvalue= "100"
Allowblank= "false" runat= "Server" >

Finally, it is important to note that the class I created is less perfect than the existing validation, and one obvious need to improve is that we need to add client script to the class so that the validation behavior can be triggered not only on the server side, but also on the client

I want everyone to understand how it works so that you can fix it when you have a better idea, and maybe one day I might use the perfect set of classes you created.



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.