Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

ASP.NET validation controls

ASP.NET validation controls validate the input data to ensure data is correct, authenticated and valid.

Asp.net uses following ready validation controls:

a.  RequiredFieldValidator
b. RangeValidator
c. CompareValidator
d. RegularExpressionValidator
e. CustomValidator
f. ValidationSummary

BaseValidator Class

All validation control classes are inherited from the BaseValidator class hence they inherit its properties and methods.

Following are Class members of BaseValidator Class:

ValidationGroup: The logical group of multiple validators used.
ControlToValidate:  input control to validate.
Display: Indicates how the error message is shown.
EnableClientScript: Indicates whether client side validation will take.
Enable: To enable or disable validation.
ErrorMessage:Indicates error string.
Text:    Error text to be shown if validation fails.
IsValid:Indicates whether the value of the control is valid.
SetFocusOnError:It indicates whether in case of an invalid control, the focus should switch to the related input control.
Validate (): This method revalidates the control and updates the IsValid property.

 

1.  RegularExpressionValidator Control:

The RegularExpressionValidator used to validate the input text by matching against a pattern of a regular expression.

 The regular expression is set in the ValidationExpression property.

Example:

 Task Id: <input type="text" id="searchParameter" runat="server" /> 
        <asp:RegularExpressionValidator id="PageRegularExpressionValidator"
                 ControlToValidate="searchParameter"
                 ValidationExpression="^\d+"
                 Display="Static"
                 ErrorMessage="Only Numbers"
                 EnableClientScript="True"
                 runat="server"></asp:RegularExpressionValidator>

 

2.  RangeValidator Control:

The RangeValidator control used to verify that the input value falls within a predetermined range.   

Example:

page size: <input type="text" id="pageSize" runat="server" /> 
        <asp:RangeValidator ID="pageSizeRange " runat="server" ControlToValidate="pageSize"
   ErrorMessage="Enter page size(2-25)" MaximumValue="25"
   MinimumValue="2" Type="Integer">
  
</asp:RangeValidator>

 

3. CompareValidator Control:

The CompareValidator control allows you to compare the value entered by the user into an input control, such as a TextBox control, with the value entered into another input control, or with a constant value. You can also use the CompareValidator control to determine whether the value entered into an input control can be converted to the data type specified by the Type property.

Example:

    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
    <asp:TextBox ID="txtxConfirmPass" runat="server" TextMode="Password"></asp:TextBox>
  <asp:CompareValidator ID="PassCompareValidator" runat="server"
    ControlToValidate="txtxConfirmPass"
    CssClass="ValidationError"
    ControlToCompare="txtPassword"
    ErrorMessage="No Match"
    ToolTip="Password must be the same" />


4. RequiredFieldValidator Control:

This is frequently used validation control ensures input control (i.e. textbox) is compulsory required with some value or user enters a value.

For example, you can specify that users must fill in a Name text box before they can submit a registration form.

Example:

   Task ID: <input type="text" style="vertical-align: middle" id="searchParameter" runat="server" /> 
       <asp:Button runat="server" ID="btnFind"  OnClick="btnFind_OnClick" Text="Find"/>
      <asp:RequiredFieldValidator ID="SerchFieldRequiredFieldValidator" runat="server" ControlToValidate="searchParameter" ErrorMessage="Task id required"></asp:RequiredFieldValidator>

 

5. Validation Groups:

This is not validation control, ValidationGroup is property used to create some logical validation groups.

For example page is divided with some panels and each panel has some different logical functionality.

i.e Employee dashboard with leave details panel ,user detail panel , admin setting panel.

Here admin setting panel is independent and require validation for specific group of controls in that you can apply ValidationGroup like ValidationGroup=”AdminSettings”

 Example:

In this example user search controls used btnFind group.

   Employee Number: <input type="text" style="vertical-align: middle" id="searchParameter" runat="server" /> 
<asp:Button runat="server" ID="btnFind"  OnClick="btnFind_OnClick" Text="Find" ValidationGroup="btnFind" />
         <asp:RequiredFieldValidator ID="SerchFieldRequiredFieldValidator" runat="server" ControlToValidate="searchParameter" ValidationGroup="btnFind" ErrorMessage="Task id required"></asp:RequiredFieldValidator>

 

6. ValidationSummary:

The ValidationSummary control is not used to perform any validation but shows a summary of all errors in the page. The summary displays the values of the ErrorMessage property of all validation controls that failed validation.

Example:

   Employee Number: <input type="text" style="vertical-align: middle" id="searchParameter" runat="server" /> 
 <asp:Button runat="server" ID="btnFind"  OnClick="btnFind_OnClick" Text="Find" ValidationGroup="btnFind" />
         <asp:RequiredFieldValidator ID="SerchFieldRequiredFieldValidator" runat="server" ControlToValidate="searchParameter" ValidationGroup="btnFind" ErrorMessage="Task id required"></asp:RequiredFieldValidator>
    <asp:ValidationSummary ID="UserSEarchValidationSummary" runat="server"
   DisplayMode = "List" ShowSummary = "true" HeaderText="Errors:" ValidationGroup="btnFind" />

 

7. CustomValidator Control:

The CustomValidator control used to implement specific custom validation logic for the client side and the server side validation.

Example:

Server side validation:

            User Name:
<asp:TextBox runat="server" id="txtUserName" />
<asp:CustomValidator runat="server" id="userCustomVal" controltovalidate="txtUserName" onservervalidate="userCustomVal_ServerValidate" errormessage="The text must be at least 4 characters long!" />

C# function:

  protected void userCustomVal_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            if (e.Value.Length == 4)
                e.IsValid = true;
            else
                e.IsValid = false;
        }

Client side validation:

            User Name:
<asp:TextBox runat="server" id="txtUserName" />
<asp:CustomValidator runat="server" id="userCustomVal" controltovalidate="txtUserName" ClientValidationFunction="UserValidation" errormessage="The text must be at least 4 characters long!" />

JavaScript function:

 <script type="text/javascript">
       //syntax 
        function SomeFunction(source, arguments) {
           //user validation logic
        }
    Example:
functionValidateUserName(sender, args) {
var txtUserLength = $('c4u-user').val().length;
if (txtUserLength ==4) {
args.IsValid = true;
    } else {
//return false;
args.IsValid = false;
    }
}
    </script>

Difference between abstract class and interface

Interface:

An interface looks like a class which contains only the declaration of methods, properties, events or indexers and has no implementation for any member.

An interface can be member of class and namespace and interface has below members:

 a.      Methods

b.      Properties

c.       Indexers

d.      Events

Abstract class:

Class uses keyword abstract that enables you to create class members that are incomplete and must be implemented in a derived class.

When a method is declared as abstract in the base class then every derived class of that class must provide its own definition for that method.

Difference between abstract class and interface

Features

Interface

Abstract

Access modifiers

Access modifier is not allowed with interface members everything is default public.

Interface class name you can declare with public and internal access modifier.

An abstract class can contain access modifiers for members i.e functions, properties etc.

Multiple inheritance

A class may inherit several interfaces.

You cannot achieve Multiple inheritances with abstract class.

Implementation

Only declaration is allowed in interface.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Fields and constants

No field and constant implementation in interface.

Implementation allowed.

Use of keyword static, virtual, abstract or sealed.

You cannot use these keywords with interface.

Virtual, abstract allowed with static class but static keyword not allowed.

Use

If multiple class shares method signatures then it is better to use Interfaces.

Reuse of some common methods with new implementation then use abstract class.

Abstract class allows partial implementation.

 

Speed

Compare to abstract speed is less.

Fast

Adding functionality

If you add method to an interface we have to track all classes and implement method in those classes.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

 

Asp.net page life cycle events

1. When you run asp.net page goes through life cycle in which performs series of steps. 
2. For each stage of the life cycle of a page, the page raises events that you can handle to run your own code.

PreInit

1.  Check the IsPostBack property to determine whether this is the first time the page is being processed. 

2.  Create or re-create dynamic controls and gets and sets profile property values

3.  Set a master page dynamically and set the theme property dynamically.

4.  This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.

protected void Page_PreInit(object sender, EventArgs e)

        {

            //page PreInit code here

 

        }

Init

1.  This event fires after each control has been initialized.

2.  Each control's UniqueID is set and any skin settings have been applied.

3.  Use this event is used to read or initialize control properties and the control tree is built

4.  This event can be handled by overloading the OnInit method or creating a Page_Init handler.

protected void Page_Init(object sender, EventArgs e)
        {
            //page Init code here
 
        }

InitComplete

1.  This event is used to track view state, in this event view state values are not loaded.

2.  Use this event for processing tasks that require all initialization to be complete.

protected void Page_InitComplete(object sender, EventArgs e)
        {
            //page Init complete code here
 
        }

LoadViewState

LoadViewState event allows loading view state information into the controls.

LoadPostData

 During this phase, the contents of all the input fields are defined with the <form> tag are processed.

OnPreLoad

1.  Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.

2.  Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

protected void Page_OnPreLoad(object sender, EventArgs e)
        {
            //page OnPreLoad code here
 
        }

Load

1.  The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded.

2.  The Load event of individual controls occurs after the Load event of the page.

3.  This is the first place in the page lifecycle that all values are restored.

4.  Most code checks the value of IsPostBack to avoid unnecessarily resetting state.

5.  You may also call Validate and check the value of IsValid in this method.

6.  You can also create dynamic controls in this method.

7.  Use the OnLoad event method to set properties in controls and establish database connections.

protected void Page_Load(object sender, EventArgs e)
        {
            //page load code here
 
        }
 

LoadComplete

1. In this event loading process is completed, control event handlers are run, and page validation takes place.

2. Use this event for tasks that require that all other controls on the page be loaded.

protected void Page_LoadComplete(object sender, EventArgs e)

        {

            //page LoadComplete code here

 

        }

 

OnPreRender

1.  Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls

2.  Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.

protected void Page_OnPreRender(object sender, EventArgs e)
        {
            //page OnPreRender code here
 
        }

OnSaveStateComplete

1.  Raised after view state and control state have been saved for the page and for all controls.

2.  Before this event occurs, ViewState has been saved for the page and for all controls.

3.  Any changes to the page or controls at this point will be ignored.

4.  Use this event perform tasks that require the view state to be saved, but that do not make any changes to controls.

protected void Page_OnSaveStateComplete(object sender, EventArgs e)
        {
            //page OnSaveStateComplete code here
 
        }

Render Method

1.  This is not an event; this is a method of the page object and its controls.

2.  All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser.

3.  The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

UnLoad

1.  Last event called in the asp.net page life cycle

2.  Final cleanup is done and all resources and references, such as database connections, are freed.

3.  This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler

protected void Page_UnLoad(object sender, EventArgs e)
        {
            //page UnLoad code here
 
        }