Tuesday, 30 October 2012

New Logical Functions in SQL Server 2012 (IIF and CHOOSE)

Problem

SQL Server 2012, has new features to perform Logical Functions such as CHOOSE and IIF that can be used to perform logical operations. In this tip we take a look at some basic examples of how this could be used.

Solution

In this tip we will discuss how to utilize the below mentioned newly introduced Logical Functions in SQL Server 2012.
1. CHOOSE Logical Function
2. IIF Logical Function

Using CHOOSE Logical Function

The CHOOSE function, which is available in SQL Server 2012, will return the item at the specified index from the list of values which are available. In this example we have 3 values and we are asking to select the third value in the list which is "SQL Server 2012".

SELECT 'New SQL Server Release' = CHOOSE(3, 'SQL Server 2008', 'SQL Server 2008 R2',
'SQL Server 2012')
GO

sql server CHOOSE function

Let’s execute the below TSQL code which will use the CHOOSE function to return the month value using the CHOOSE logical function.

Use AdventureWorks2008R2
GO
SELECT 
  DISTINCT(FirstName + ' ' + LastName) AS Name
 ,DATEPART(DD, ModifiedDate) AS [Date]
 ,CHOOSE(DATEPART(MM,ModifiedDate),'January','February','March','April','May','June',
  'July','August','September','October','November','December')[Month]
 ,DATEPART(YYYY, ModifiedDate) AS [Year]
FROM [Person].[Person] 
 ORDER BY Name ASC
GO

sql server result set using the choose function in denali

Using IIF Logical Function

The IIF function, which is available in SQL Server 2012, returns one of the two values depending upon whether the Boolean expression evaluates to either True or False.

DECLARE @FirstArgument INT = 10
DECLARE @SecondArgument INT = 20
SELECT IIF ( @FirstArgument > @SecondArgument , 'TRUE', 'FALSE' ) 
 AS [Output Using IIF Logical Function]
GO

sql server 2012 iif logical function

Let’s execute the below TSQL code which will use the IIF function to return the results. The logic is if the StateProvinceCode is between 0 and 95 then return France otherwise return Canada.

Use AdventureWorks2008R2
GO
SELECT 
   StateProvinceCode
  ,CountryRegionCode
  ,IIF(TRY_PARSE(StateProvinceCode AS INT) Between 0 AND 95,'France','Canada') AS Country
FROM Person.StateProvince 
  WHERE StateProvinceCode IN ('95','AB')
GO

sql server 2012 iif logical function

Saturday, 27 October 2012

Insert|Select|Update and Delete Records in a Single Stored Procedure Using SQL Server

Background
Sometimes there is a need to insert, select, update and delete records from a table using a single Stored Procedure instead of creating separate Stored Procedures for each operation.

Suppose I have one .aspx web page in which I need a to insert, select, update and delete records. To do that instead of creating four Stored Procedures to perform these tasks I will create a single Stored Procedure to satisfy my requirements and I will access it in code behind according to the action performed by the end user on a button click.

I have written this article specially focusing on newcomers and anyone new to SQL Stored Procedures so let us start with a basic introduction.

What is Stored Procedure?A Stored Procedure is a group of logical SQL statements to perform a specific task such as insert, select, update and delete operations on a table and so on which is stored in a SQL database.

Creating a Stored Procedure

Before creating a Stored Procedure, we will create one table named employee in the SQL database which looks as in the following image.

I have set the primary key on the id column for the Identy specification.
 
creatingtbl.png
 

 

 

 

 



 
Now we have a table to perform these operations. Now let us start to create the Stored Procedure.
The Stored Procedure is created using the keyword Create Procedure followed by the procedure name. Let us create the Stored Prcedure named EmpEntry as given below.

create Procedure EmpEntry
(
 --variable  declareations

@Action Varchar (10),                             --to perform operation according to string passed to this varible such as Insert,update,delete,select    
@id int=null,                                   --id to perform specific task 

@Fname Varchar (50)=null,                     -- for FirstName 
@MName Varchar (50)=null,                    -- for MName
 @Lname Varchar (50)=null                      -- for LastName
)------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---exec EmpEntry @Action='delete' ,@Fname='S',@MName='R',@Lname='M',@id='13'  -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
as
Begin
  SET NOCOUNT ON;
If @Action='Insert'   --used to insert records 
Begin 
Insert Into employee (FirstName,MName,LastName)values(@Fname,@MName,@Lname)
 End  
else if @Action='Select'   --used to Select records 
Begin
 select *from employee 
end
else if @Action='Update'  --used to update records
 Begin
  update employee set FirstName=@Fname,MName=@MName,LastName=@Lname where id=@id 
 End 
Else
 If @Action='delete'  --used to delete records
  Begin
 delete from employee where id=@id
 
end
 End

In the above Stored Procedure throught comments I have clearly explained which block is used for which purpose, so I have briefly explained it again. I have used @Action variable and assigned the string to them and according to the parameter passed to the Stored Procedure the particular block will be executed because I have kept these blocks or conditions in nested If else if conditional statements.

 "The most important thing is that I have assigned null to each variable to avoid the effect on the parameter passed to the Stored Procedure because we are passing a different number of parameters but not the same number of parameters to the Stored Procedure to perform these tasks." 

After creating this Stored Procedure, now let us use it.

To execute the Stored Procedure EmpEntry that we created we need to use the keyword exec followed by the procedure name and the parameter list. I have explained how to use it below.

Inserting the Records into the Employee table that we created with the EmpEntry procedure; see:
exec EmpEntry @Action='Insert',@Fname='Ramesh',@MName='Kumar',@Lname='Kashaudhan'
After running this query the records will be inserted into the table employee. To see the records inserted into the table the run following query:
select * from employee

How to Find ASP.NET Control and get/Set values of Controls in ASP.NET using JavaScript


At a time there becomes a requirement to get/set the values of controls in our project. We can get/set the values of controls through programming or by using JavaScript. If we just have to perform a get/set operation we can do it by simply using JavaScript.

Scenario I

Let's consider a scenario where I've 2 textboxes named TextBox1 and TextBox2 and I need to set the value of a particular textbox in the other textbox on the same page.

I can simply do it programmatically with the following line.

TextBox2.Text=TextBox1.Text;

The same part of code can be done by using JavaScript:

document.getElementById('<%=TextBox2.ClientID%>').value=document.getElementById('<%=TextBox1.ClientID%>').value

or

document.forms[0]["TextBox2"].value=document.forms[0]["TextBox1"].value;

Note: Provided that the pages are just normal web page and don't have any master page applied to it.

Scenario II

Now consider a scenario if we have a master applied on a particular web page and we want to get/set the value of a particular control within the same web page.

For doing this activity we'll create a sample master page. The following is the code for the master page.

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="TopLevel.master.cs" Inherits="TopLevel" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
        .style1
        {
            width: 4%;
        }
        .style2
        {
            width: 1274px;
        }
    </style>
</head>
<
body>
 <form id="form1" runat="server">
<table style="width:100%;">
        <tr>
            <td align="right" colspan="3">
                <asp:Image ID="Image1" runat="server" ImageUrl="~/images/AdvWorksLogo.gif" />
            </td>
        </tr>
        <tr>
            <td class="style1">
                <asp:Image ID="Image2" runat="server" ImageUrl="~/images/AdvWorksSideBar.gif" />
            </td>
            <td valign="top" class="style2">
        <asp:ContentPlaceHolder id="pageContent" runat="server">
            <p>
                <br />
            </p>
            <p>
            </p>
            <p>
            </p>
            <p>
            </p>
           
        </asp:ContentPlaceHolder>
            </td>
            <td style="width: 10%">
                &nbsp;</td>
        </tr>
        <tr>
            <td align="right" colspan="3">
                <asp:Label ID="Label1" runat="server"
                    Text="&lt;b&gt;Copyright&amp;copy;2011@AdventureWork.com&lt;/b&gt;"></asp:Label>
            </td>
        </tr>
    </table>
    </form>
</body>
</
html>

Following is the source code for the Test.aspx apge.

<%@ Page Language="C#" MasterPageFile="~/TopLevel.master" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test1" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="pageContent" Runat="Server">
    <script type="text/javascript">
    function getData()
    {
        /*
        Here your this method of setting the value will not work because in our current web page we donot have a form tag we have a content tag
        which is inside the master page. So our form tag will reside on master then how do i access/set the value through this method.
            document.forms[0]["TextBox2"].value=document.forms[0]["TextBox1"].value;
        */
        document.getElementById('<%=TextBox2.ClientID %>').value=document.getElementById('<%=TextBox1.ClientID %>').value;
          /*
          OR
              var a = document.getElementById('<%= "ctl00_pageContent_TextBox1" %>').value;
            document.getElementById('<%= "ctl00_pageContent_TextBox2" %>').value = a;
          */     
    }
</script>
    <table style="width: 40%;">
        <tr>
            <td>
                Enter Your Name :
            </td>
            <td>
              <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </td>
            </tr>
            <tr>
            <td colspan="2" align="center">
                   <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="getData()" />
            </td>
            </tr>
        <tr>
            <td>Your Name is :</td>
            <td>
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
        </tr>
    </table>
</asp:Content>

NOTE : In case you want to access a master page control on the child page you can use the following code.

document.getElementById('<%=Page.MasterPage.FindControl("pageContent").FindControl("TextBox2").ClientID %>').value=document.getElementById('<%=Page.MasterPage.FindControl("pageContent").FindControl("TextBox1").ClientID %>').value

Hope you've liked the article.

 

Thursday, 25 October 2012

$linq – A Javascript LINQ library v1.0 Released

Few days back, $linq v1.0 was released which is now available for download from codeplex website.

$linq is a Javascript version of .NET’s LINQ to Objects and implements most of the corresponding .NET LINQ to Objects methods like select , select many, where, order by, distinct, group by, join, except etc.

$linq also implements some of the methods that are inspired by MoreLinq and can work with arrays and JQuery collections

Below is a sample program


var people = [{ Name: "Senthil Kumar"},

{ Name: "Norton Stanley"},

{ Name: "Pavam M"}];

var filteredData = people.where("x => x ='Norton Stanley'").toArray();

Download $linq – A Javascript LINQ library from Codeplex

Wednesday, 24 October 2012

ValidationControls |TextArea validation using RegularExpressionValidator |ValidationSummary using ValidationGroup Date Validation using RegularExpressionValidator



Asp.Net - using ValidationControls with ValidationSummary 

In Asp.Net we can use the Validation controls which come built in with Asp.net. Asp.Net offers the following validation controls.

RequiredFieldValidator
RegularExpressionValidator
CompareValidator
CustomValidator
RangeValidator

Now suppose we have multiple controls in a form, and each controls is associated with one or more validation controls, we will have to display the summary of all the validation in a single messagebox, to do so we can make use of the ValidationSummary control.

For example let us consider a textbox, which can accept only US Phone numbers, let us try to do the validation for this controls and associate the same with a ValidationSummary control.
Open an Asp.net page and add the control and the validationcontrol

<asp:TextBox
id="txtBusinessOwnerPhone"
runat="server"
CssClass="text"
MaxLength="12">
</asp:TextBox>
<asp:RegularExpressionValidator
ID="valtxtBusinessOwnerPhone"
runat="server"
ControlToValidate="txtBusinessOwnerPhone"
ValidationExpression="[0-9]{3}[-]{1}[0-9]{3}[-]{1}[0-9]{4}[-]"
Display="None"
Text="*"
ErrorMessage="Enter Phone# in the format 999-999-9999">
</asp:RegularExpressionValidator>

Now we have the TextBox Control and a RegularExpressionValidator control to validate the same, we should add a ValidationSummary control to handle all the validations in the page, we shall add the summary control, below the Submit button.

<asp:Button ID="cmdSave" runat="server" Text="Save"/>
<
asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
EnableClientScript="true"/>

Now build and run the project, enter an invalid Phone number in the textbox and click on the Save button.



That's it, we have implemented the ValidationSummary control for the Asp.Net Validation controls.

2. Asp.Net - Date Validation using RegularExpressionValidator 


Date validation using Asp.Net RegularExpressionValidator
Asp.Net offers the following validation controls.

RequiredFieldValidator
RegularExpressionValidator
CompareValidator
CustomValidator
RangeValidator

To validate the date, we can use the RegularExpressionValidator. This validator requires a regular expression which will validate the pattern of data entered in the control.


Open an Asp.net page and add a TextBox control, also add a RegularExpressionValidator control to validate the date entered in the TextBox


<asp:TextBox ID="txtDate" runat="server">asp:TextBox>
<
asp:RegularExpressionValidator
ID="val txtDate "
runat="server"
ControlToValidate=" txtDate "
Display="None"
ErrorMessage="Enter a valid Date, Format (mm/dd/yyyy)"
SetFocusOnError="True"
ValidationExpression="^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$">
*asp:RegularExpressionValidator>

Now we have the TextBox Control and a RegularExpressionValidator control to validate the same, we should add a ValidationSummary control to handle all the validations in the page, we shall add the summary control, below the Submit button.

<asp:Button ID="cmdSave" runat="server" Text="Save"/>
<
asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
EnableClientScript="true"/>

Now build and run the project, enter an invalid Date in the textbox and click on the Save button.
You should get the Error message as follows.




3-Asp.Net - ValidationSummary using ValidationGroup 

In Asp.Net the ValidationSummary control consolidates the validation detials and error messages of all the validation controls in the page and provides a summary report of all the validation failures in the page.


Suppose we have a large page and we need to group the validations in the page based on specific groups, here we need to use the ValidationGroup property, the ValidationGroup property should be set to the controls which are part of the group, the ValidationSummary control and the button which will handle the submit/postback of this group.

Here’s the code below


<
asp:TextBox id="txtPhone" runat="server" CssClass="text" MaxLength="12">asp:TextBox>

<asp:RegularExpressionValidator ID="valtxtPhone" runat="server" ControlToValidate="txtPhone" ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}" Display="None" Text="*" ValidationGroup="valGroup" ErrorMessage="Enter Phone# in the format 999-999-9999" SetFocusOnError="true">asp:RegularExpressionValidator>

<asp:Button ID="cmdSave" runat="server" Text="Save" ValidationGroup="valGroup" />

<asp:ValidationSummary ID="valSummary" runat="server" DisplayMode="List" ValidationGroup="valGroup" ShowMessageBox="True" ShowSummary="False" EnableClientScript="true"/>

Now build and run the project, enter an invalid Phone# in the textbox and click on the Save button. You should get an error message.

Also notice that other validations in the page, which are not bound to this ValidationGroup will not get fired.

That's it, we have implemented the ValidationGroup in the ValidationSummary control for the Asp.Net Validation controls.


4-Asp.Net - TextArea validation using RegularExpressionValidator 

The Asp.Net TextArea control doesnot support the MaxLength property, though you set the MaxLength property, the TextArea control will not restrict the users to enter text within the set limit. The MaxLengh property works fine with the TextBox controls, but when it comes to TextArea controls (TextMode = MultiLine) the MaxLength property fails.

The RegularExpressionValidator, control can be used to validate the MaxLength property of the TextArea control. Her’s how this can be accomplished.

Add a TextBox control to your Asp.net form and set its TextMode property to MultiLine, then add a RegularExpressionValidator control with the regular expression to restrict the length of the text in the TextBox.

Here’s the code

<asp:TextBox id="txtProjectDescription"
 runat="server"
 CssClass="text"
 MaxLength="2500"
 Width="500px"
 TextMode="MultiLine"
 Rows="5">
asp:TextBox>

<asp:RegularExpressionValidator
ID="valtxtProjectDescription"
runat="server"
ControlToValidate="txtProjectDescription"
Display="None"
ErrorMessage="Project Description Should be less than 2500 Characters"
SetFocusOnError="True"
ValidationExpression="^([\S\s]{0,2500})$">
asp:RegularExpressionValidator>

Add the Save Button and the Validation Summery control
<asp:Button
ID="cmdSave"
runat="server"
Text="Save"
/>

<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
EnableClientScript="true"/>

Now build and run the project, enter a text with length more that 2500 characters in the TextArea. You should get an error message 

Project Description Should be less than 2500 Characters


5-RangeValidator in Asp.Net 

The RangeValidator is used to make sure that the user enters a value within a pre-defined range of values, this validate is often used to validate numeric value inputs from the user.

The below code snipet adds a TextBox to an Asp.net form and associates an Asp.Net RangeValidator to the text box to make sure that the text box accepts only values in the range 1.. 1000

<asp:TextBox
ID="txtID"
runat="server"
MaxLength="25">
</asp:TextBox>

<asp:RangeValidator
ID="valtxtID "
runat="server"
ControlToValidate="txtID"
          Display="Dynamic"
ErrorMessage="Please enter a valid number (1..1000)."
MinimumValue="1"
MaximumValue="1000"
Type="Integer"
SetFocusOnError="True">*
</asp:RangeValidator>

The above RangeValidator makes sure that only numeric values in the range 1..1000 are entered in the txtID textbox, any other values will lead to an error message prompt.

The RangeValidator
 also takes care of the datatype of the value which is entered in the TextBox, the Type="Integer" property makes sure that only Integer values are entered into the TextBox.

Finally add a ValidationSummary control to consolidate all the validations in the page.



<asp:Button ID="cmdSave"
runat="server"
Text="Save"
OnClick="cmdSave_Click" />
              
<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
      ShowSummary="False"
EnableClientScript="true" />
</asp:ValidationSummary>

Once we are done with the code in the .aspx page, we should also make sure that the validations are passed in the server side in the .vb/.cs code behind file.

Asp.Net performs the validations both in the client and the server side, of the users' browser doesn’t support JavaScript then the client side validation might get skipped, however the same validation in done by Asp.Net in the server side also. 

The
 Page.IsValid property returns true if the server side validations are succesful, else it will return false, hence we need to make sure that the Page.IsValid property is true before proceeding with the other operations.

if (Page.IsValid)
{
   //DB save and other server side logic goes here
}
 
That’s it we have seen, how to use the RangeValidator to validate user input in an Asp.net form.


6-RequiredFieldValidator in Asp.Net 

As the name implies, the RequiredFieldValidator is used to make sure that the user enter a value for a specific field in the form.

A RequiredFieldValidator can be associated with a control which cannot be empty while submitting the form.

The below code snipet adds a TextBox to an Asp.net form and associates an Asp.Net RequiredFieldValidator to the text box to make sure that the Name is entered before submitting the form.

<asp:TextBox
ID="txtName"
runat="server"
MaxLength="250">
</asp:TextBox>
                                                                <asp:RequiredFieldValidator
ID="valtxtName"
runat="server"
ControlToValidate="txtName"                                                                    Display="Dynamic"
ErrorMessage="Please enter Name."
SetFocusOnError="True">*
</asp:RequiredFieldValidator>

The RequiredFieldValidator also takes care of the white spaces in the TextBox, the validator makes sure that the user does not just type some white spaces and submit the form, it makes sure that a valid Character or Number is entered before submitting the form.

Finally add a ValidationSummary control to consolidate all the validations in the page.


<asp:Button ID="cmdSave"
runat="server"
Text="Save"
OnClick="cmdSave_Click" />
              
<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
      ShowSummary="False"
</EnableClientScript="true" />

Once we are done with the code in the .aspx page, we should also make sure that the validations are passed in ther server side in the .vb/.cs code behind file.

Asp.Net performs the validations both in the client and the server side, of the users' browser doesn’t support JavaScript then the client side validation might get skipped, however the same validation in done by Asp.Net in the server side also.

The Page.IsValid property returns true if the server side validations are succesful, else it will return false, hence we need to make sure that the Page.IsValid property is true before proceeding with the other operations.

if (Page.IsValid)
{
   //DB save and other server side logic goes here
}
 

That’s it we have seen, how to use the RequiredFieldValidator to validate user input in an Asp.net form


7- Asp.net CustomValidator – JavaScript client side validation 

As the name implies, the CustomValidator is used to perform custom validations in an Asp.Net page, the CustomValidator is very handy when we need to perform complex validations involving more than one control in an Asp.net page.

CustomValidator can be associated with either a client side JavaScript function or with a server side VB.Net/C# function. In this post we shall see on how to use the CustomValidator for client side JavaScript validation.


The below code snippet adds a DropDownList and a TextBox control to an Asp.net form with an Asp.Net CustomValidator which validates the combination of values from both these controls.

Condition to validate: If others is selected in the drpCountry DropDownList, then the txtName TextBox should not be empty.

Select Country:
<asp:DropDownList ID="drpCountry" runat="server">
    <asp:ListItem>India</asp:ListItem>
    <asp:ListItem>USA</asp:ListItem>
    <asp:ListItem>UK</asp:ListItem>
    <asp:ListItem>Others</asp:ListItem>
</asp:DropDownList><br />

<asp:Label ID="lblText" runat="server" Text="If Others enter Country Name: " />
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
    <asp:Button ID="cmdSave" Text="Submit" runat="server"/>
    <br />
    <br />
<asp:CustomValidator
    ID="valCountry"
    ControlToValidate="drpCountry"
    ClientValidationFunction="validateCountry"
    Text="Please enter Country Name"
    runat="server"/>

The ClientValidationFunction property of the CustomValidator calls the JavaScript function validateCountry.

Here is the JavaScript function

<script type="text/javascript" language="javascript">

    function validateCountry(oSrc, args)
    {
        vSelection = document.getElementById("drpCountry");
        vName = document.getElementById("txtName");
        if(vSelection.value != "Others")
        {
            args.IsValid = true;
            return;
        }
        //   
        if (vName.value.length == 0)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }
    }
</script>


Now if you try to save the form by selecting Others in the drpCountry DropDownList with an empty value in the txtName TextBox then the validation fires and displays the message.

Please enter Country Name

That’s it we have seen the usage of a CustomValidator with JavaScript validation.

8-Asp.net CustomValidator - Server side validation 

As the name implies, the CustomValidator is used to perform custom validations in an Asp.Net page, the CustomValidator is very handy when we need to perform complex validations involving more than one control in an Asp.net page.

CustomValidator  can be associated with either a client side JavaScript function or with a server side VB.Net/C# function. In this post we shall see on how to use the CustomValidator for server side validation.


 
The below code snippet adds a DropDownList and a TextBox control to an Asp.net form with an Asp.Net CustomValidator which validates the combination of values from both these controls.

Condition to validate: If Others is selected in the drpCountry DropDownList, then the txtName TextBox should not be empty.

Select Country:
<asp:DropDownList ID="drpCountry" runat="server">
    <asp:ListItem>India</asp:ListItem>
    <asp:ListItem>USA</asp:ListItem>
    <asp:ListItem>UK</asp:ListItem>
    <asp:ListItem>Others</asp:ListItem>
</asp:DropDownList><br />

<asp:Label ID="lblText" runat="server" Text="If Others enter Country Name: " />
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
    <asp:Button ID="cmdSave" Text="Submit" runat="server"/>
    <br />
    <br />
<asp:CustomValidator
    ID="valCountry"
    ControlToValidate="drpCountry"
    OnServerValidate="validateCountry"
    Text="Please enter Country Name"
    runat="server"/>

The OnServerValidate property of the CustomValidator calls the server side function validateCountry.

Here is the server side (code-behind) function

public void validateCountry(object source, ServerValidateEventArgs args)
{
    if (drpCountry.SelectedValue != "Others")
    {
        args.IsValid = true;
        return;
    }
    //
    if (txtName.Text.Trim().Length == 0)
    {
        args.IsValid = false;
    }
    else
    {
        args.IsValid = true;
    }
}

Now if you try to save the form by selecting Others in the drpCountry DropDownList with an empty value in the txtName TextBox then the validation fires and displays the message.

Please enter Country Name

That’s it we have seen the usage of a CustomValidator with server side validation.


9-Disable asp.net validation controls in JavaScript 

In this post Disable asp.net validation controls in JavaScript; we will see on how to disable Asp.Net validation controls using JavaScript.

Asp.net validation controls are server side controls, but we might need to disabled them at times, these controls can be disabled from the server side code using the .Enabled property as follows.
validateName.Enabled = false;

But, disabling the controls from the code-behind will require a page post back; to avoid this we can disable the Validation controls from the client side using Java Script as follows.

var myValidator = document.getElementById('validateName');
ValidatorEnable(myValidator, false);

You might wonder that we have not defined the function ValidatorEnable, and might throw an error, but no errors will be thrown, this is a Built in function in Asp.Net



Here is a full example
<script type="text/javascript">
function DisableValidator(checked)
{
    if (checked == true)
    {
        var myValidator = document.getElementById('validateName');
        ValidatorEnable(myValidator, false);
    }
}
</script>

Enter Name:
<asp:TextBox
    ID="txtName"
    runat="server">
</asp:TextBox>

<asp:RequiredFieldValidator
    ID="validateName"
    runat="server"
    ControlToValidate="txtName"
    ErrorMessage=" Please enter Name"
    Display="Dynamic">
</asp:RequiredFieldValidator><br />

Disable Validator:
<input
    type="checkbox"
    value="Disable Validator"
    onclick="javascript:DisableValidator(this.checked);" /><br />

<asp:Button
    ID="cmdSave"
    runat="server"
    Text="Save" onclick="cmdSave_Click"/>

In the above example when the Disable Validator checkbox is checked, the validator validateName is disable, hence the user can submit the form without entering the name, but when the checkbox is not checked the user is prompted with an error message Please enter Name, when the txtName TextBox is empty