<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ColdFusion cfdirectory tag example: how to get file and directory list under a directory</title>
</head>
<body>
<h2 style="color:DodgerBlue">ColdFusion cfdirectory tag example: List</h2>
<cfset CurrentDirectory=GetTemplatePath()>
<cfset CurrentDirectory=ListDeleteAt(CurrentDirectory,ListLen(CurrentDirectory,"/\"),"/\")>
<cfoutput>
<b>Current Directory:</b> #CurrentDirectory#
<br />
</cfoutput>
<cfdirectory action="list" directory="#CurrentDirectory#" name="result">
<cfdump var="#result#">
</body>
</html>
How to get file and directory list under a directory in coldfusion
How to delete directory programmatically in coldfusion
Introduction
In web development, managing server-side file systems efficiently is an essential task. Adobe ColdFusion offers several useful tags and functions to interact with files and directories, including the ability to programmatically create, modify, and delete directories. In this tutorial, we will explore how to delete a directory using the ColdFusion <cfdirectory>
tag. This functionality is particularly useful for developers needing to automate file system management tasks, such as cleaning up unused directories or managing temporary files generated by web applications.
This example demonstrates how to check if a directory exists on the server and, if it does, delete it using ColdFusion's native tags. We will walk through the structure and logic of the code, providing clear explanations of how it works and how you can apply it to similar scenarios.
Displaying the Current Directory
The code starts by setting the path of the directory we want to work with using the cfset
tag. In this case, the path C:\TestDirectory
is stored in the CurrentDirectory
variable. This path represents the directory we intend to check and potentially delete.
The use of the <cfoutput>
tag helps in dynamically displaying the directory path on the webpage. This step is useful for debugging purposes, as it allows you to see which directory is currently being targeted before any actions are taken. When running the script, it will output a line like "Current Directory: C:\TestDirectory", which gives the user immediate feedback on the directory's location.
Checking if the Directory Exists
Before attempting to delete the directory, it's essential to ensure that it exists. ColdFusion's DirectoryExists()
function is used here to check whether the specified directory is present on the server. This function returns a Boolean value—true
if the directory exists, and false
otherwise.
In the code, the existence of the directory is evaluated inside a <cfif>
conditional block. If the directory is found, the code proceeds to delete it. If it does not exist, a message is output stating that the directory does not exist. This step ensures that unnecessary deletion attempts are avoided, preventing potential errors or performance issues.
Deleting the Directory
The key part of this example is the <cfdirectory>
tag, which is used to perform actions on directories. In this case, the action specified is "delete"
, which instructs ColdFusion to remove the directory at the path specified by the directory
attribute. The directory path is dynamically passed to the tag using #CurrentDirectory#
, ensuring that the directory specified earlier is deleted if it exists.
Once the directory is successfully deleted, a confirmation message ("Directory deleted!") is displayed to the user. This feedback is critical for informing the user that the operation has been completed without any issues.
Handling Non-Existent Directories
In the event that the directory does not exist, the code enters the <cfelse>
block, where it outputs a message stating that the specified directory does not exist. This is a graceful way of handling scenarios where the deletion action is unnecessary, and it prevents errors that could arise from trying to delete something that isn't there.
Conclusion
This tutorial showcases how ColdFusion's <cfdirectory>
tag can be leveraged to manage server-side directories efficiently. By checking if a directory exists before attempting to delete it, we can avoid unnecessary operations and potential errors. This process is simple yet powerful for automating file system tasks in web applications.
With the ability to delete directories programmatically, developers have greater control over the file systems their applications interact with. Whether it’s for routine maintenance, cleanup, or other file management tasks, understanding how to use the <cfdirectory>
tag is an essential skill for ColdFusion developers.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ColdFusion cfdirectory tag example: how to delete directory programmatically</title>
</head>
<body>
<h2 style="color:DodgerBlue">ColdFusion cfdirectory tag example: Delete</h2>
<cfset CurrentDirectory="C:\TestDirectory">
<cfoutput>
<b>Current Directory:</b> #CurrentDirectory#
<br />
</cfoutput>
<cfif DirectoryExists(CurrentDirectory)>
<cfdirectory action="delete" directory="#CurrentDirectory#">
<i>Directory deleted!</i>
<cfelse>
<cfoutput>
#CurrentDirectory# Directory not exists!
</cfoutput>
</cfif>
</body>
</html>
ColdFusion: How to create a directory programmatically
Introduction
In this tutorial, we will explore how to programmatically create a directory using Adobe ColdFusion. ColdFusion is a powerful server-side scripting language, and one of its key features is the ease with which it can interact with the file system. By using the <cfdirectory>
tag, ColdFusion allows developers to perform various directory operations, including creating, reading, and deleting directories. In this example, we focus on creating a new directory dynamically.
Creating directories programmatically is a common task in web development, particularly when building applications that manage files or allow users to upload content. With ColdFusion, this process is simple and efficient. The tutorial walks through how to set up the environment, generate a new folder, and ensure that the directory is created in the desired location.
Setting the Current Directory Path
The first step in this example involves determining the current directory where the ColdFusion template is running. The ColdFusion function GetTemplatePath()
is used to retrieve the absolute path of the file being executed. This function returns the full file path of the current .cfm
file.
Once we have the full path, we need to clean it up to remove the actual file name, so that only the directory path remains. This is achieved by using the ListDeleteAt()
function, which removes the last element of the directory path, typically the name of the file itself. The result is the directory in which the file resides, and this will serve as the starting point for creating our new directory.
Defining the New Directory
Now that we have the current directory, the next step is to define the path for the new directory we want to create. In this case, a folder named TestFolder
is appended to the current directory path. This new path represents the directory that will be generated. By using string interpolation (#CurrentDirectory#\TestFolder
), ColdFusion constructs the full path for the new directory.
To help the developer or user visually understand the process, the code outputs both the current directory and the new directory path using the <cfoutput>
tag. This is helpful for debugging and confirming that the paths are correct before proceeding with the directory creation.
Creating the Directory with <cfdirectory>
The <cfdirectory>
tag is a powerful feature in ColdFusion that allows developers to interact with the file system. In this example, the action="create"
attribute is used, which instructs ColdFusion to create the directory at the specified path. The directory
attribute holds the path to the new folder (#NewDirectory#
), which we defined in the previous step.
ColdFusion will attempt to create the directory at runtime, and if successful, the folder TestFolder
will be added to the current directory. The simplicity of this tag hides the complexity of file system operations, making it an efficient tool for developers.
Conclusion
In this tutorial, we demonstrated how to use ColdFusion’s <cfdirectory>
tag to create a directory programmatically. By leveraging functions like GetTemplatePath()
and ListDeleteAt()
, we were able to dynamically determine the current file path and then append a new directory name. This process showcases the ease and power of ColdFusion for file management tasks.
Whether building a file upload system, an image gallery, or any application that requires directory manipulation, the <cfdirectory>
tag simplifies the process. It offers a flexible and reliable way to handle directories without the need for complex file system code, making it an essential tool in a ColdFusion developer’s toolkit.
<!DOCTYPE html">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ColdFusion cfdirectory tag example: how to create directory programmatically</title>
</head>
<body>
<h2 style="color:DodgerBlue">ColdFusion cfdirectory tag example: Create</h2>
<cfset CurrentDirectory=GetTemplatePath()>
<cfset CurrentDirectory=ListDeleteAt(CurrentDirectory,ListLen(CurrentDirectory,"/\"),"/\")>
<cfset NewDirectory="#CurrentDirectory#\TestFolder">
<cfoutput>
<b>Current Directory:</b> #CurrentDirectory#
<br />
<b>New Directory:</b> #NewDirectory#
</cfoutput>
<cfdirectory action="create" directory="#NewDirectory#">
</body>
</html>
ColdFusion CFdbinfo - How to get column list from a table
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ColdFusion cfdbinfo tag example: how to get column list from a table</title>
</head>
<body>
<h2 style="color:DodgerBlue">ColdFusion cfdbinfo tag example: Column List</h2>
<cfdbinfo datasource="cfbookclub" table="Books" type="columns" name="result">
<cfquery dbtype="query" name="qColumnList">
SELECT COLUMN_NAME FROM result
</cfquery>
<cfdump var="#qColumnList#">
</body>
</html>
- cfdbinfo - get table name list from a datasource
- cfdbinfo - get system table name list from a datasource
- cfgrid - display data in a flash format grid
- cfgrid - display data in a applet format grid
- cfgrid - display data in a html format grid
- cflocation - redirect a page with token
- cfinvoke - invoke a method of a component
- cfinvoke and cfinvokeargument - invoke a method of a component
- cfquery - insert data
asp.net - How to use custom image in a TreeView
The following ASP.NET C# tutorial code demonstrates how we can use custom images in a TreeView web server control. The asp.net c# developers can alter the appearance of the control to customize the images that are displayed in the TreeView control.
The ASP.NET C# developers can specify their own custom set of images for the different parts of the TreeView control by setting the CollapseImageUrl, ExpandImageUrl, LineImagesFolder, and NoExpandImageUrl properties.
The TreeView CollapseImageUrl property is the URL to an image displayed for the collapsible node indicator. This image is usually a minus sign (-). The ExpandImageUrl is the URL to an image displayed for the expandable node indicator. This image is usually a plus sign (+).
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to use custom image in TreeView Control</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">TreeView Example: Using Custom Image</h2>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
<asp:TreeView
ID="TreeView1"
runat="server"
DataSourceID="SiteMapDataSource1"
ExpandImageUrl="~/Images/Expand.jpg"
CollapseImageUrl="~/Images/Collapse.jpg"
LeafNodeStyle-ImageUrl="~/Images/Leaf.jpg"
>
</asp:TreeView>
</div>
</form>
</body>
</html>
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="~/Default.aspx" title="Home" description="Home Page">
<siteMapNode url="~/Design.aspx" title="Design" description="Design Tools">
<siteMapNode url="~/Photoshop.aspx" title="Photoshop" description="Adobe Photoshop" />
<siteMapNode url="~/Firaworks.aspx" title="Firaworks" description="Adobe Firaworks" />
</siteMapNode>
<siteMapNode url="~/Development.aspx" title="Development" description="Development Tools">
<siteMapNode url="~/ColdFusion.aspx" title="ColdFusion" description="Adobe ColdFusion" />
<siteMapNode url="~/aspnet.aspx" title="asp.net" description="Microsoft asp.net" />
</siteMapNode>
</siteMapNode>
</siteMap>
How to get System Table names from a DataBase in ColdFusion
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ColdFusion cfdbinfo tag example: how to get system table name list from a datasource</title>
</head>
<body>
<h2 style="color:DodgerBlue">ColdFusion cfdbinfo tag example: System Table List</h2>
<cfdbinfo datasource="cfartgallery" type="tables" name="qResult">
<cfquery dbtype="query" name="qSystemTableList">
SELECT TABLE_NAME FROM qResult
WHERE TABLE_TYPE='SYSTEM TABLE'
</cfquery>
<cfdump var="#qSystemTableList#">
</body>
</html>
- cfdbinfo - get table name list from a datasource
- cfdbinfo - get column list from a table
- cfgrid - display data in a flash format grid
- cfgrid - display data in a applet format grid
- cfgrid - display data in a html format grid
- cflocation - redirect a page with token
- cfinvoke - invoke a method of a component
- cfinvoke and cfinvokeargument - invoke a method of a component
- cfquery - insert data
How to get Table names from a DataBase in ColdFusion
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ColdFusion cfdbinfo tag example: how to get table name list from a datasource</title>
</head>
<body>
<h2 style="color:DodgerBlue">ColdFusion cfdbinfo tag example: Table List</h2>
<cfdbinfo datasource="cfbookclub" type="tables" name="result">
<cfquery dbtype="query" name="qTableList">
SELECT TABLE_NAME FROM result
WHERE TABLE_TYPE='TABLE'
</cfquery>
<cfdump var="#qTableList#">
</body>
</html>
- cfdbinfo - get system table name list from a datasource
- cfdbinfo - get column list from a table
- cfgrid - display data in a flash format grid
- cfgrid - display data in a applet format grid
- cfgrid - display data in a html format grid
- cflocation - redirect a page with token
- cfinvoke - invoke a method of a component
- cfinvoke and cfinvokeargument - invoke a method of a component
- cfquery - insert data
RequiredFieldValidator to validate RadioButtonList in asp.net c#
This example demonstrates to you how can we validate RadioButtonList control using RequiredFieldValidator. This validation control makes RadioButtonList a mandatory (required) field. So the user must select (check) a list item from RadioButtonList to pass the validation and submit the form. It is very useful when RadioButtonList has no default selection. If the validation fails, the RequiredFieldValidator shows a predefined error message that tells you RadioButtonList is a required field.
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Your favorite: ";
Label1.Text += RadioButtonList1.SelectedItem.Text.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net RequiredFieldValidator example: how to validate RadioButtonList</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Green">RadioButtonList Validation</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="Crimson"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="Favorite"
Font-Bold="true"
ForeColor="DodgerBlue"
>
</asp:Label>
<asp:RadioButtonList
ID="RadioButtonList1"
runat="server"
RepeatColumns="3"
BackColor="DodgerBlue"
ForeColor="AliceBlue"
BorderColor="DarkBlue"
BorderWidth="2"
>
<asp:ListItem>CheckBoxList</asp:ListItem>
<asp:ListItem>TreeView</asp:ListItem>
<asp:ListItem>Button</asp:ListItem>
<asp:ListItem>SqlDataSource</asp:ListItem>
<asp:ListItem>GridView</asp:ListItem>
<asp:ListItem>Calendar</asp:ListItem>
<asp:ListItem>BulletedList</asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator
ID="ReqiredFieldValidator1"
runat="server"
ControlToValidate="RadioButtonList1"
ErrorMessage="Select your favorite!"
>
</asp:RequiredFieldValidator>
<br />
<asp:Button
ID="Button1"
runat="server"
ForeColor="DodgerBlue"
Text="Submit Favorite"
OnClick="Button1_Click"
/>
</div>
</form>
</body>
</html>
How to use HyperLink in asp.net
HyperLink server control's other important property is the Target property. The .net developers can specify the frame or window to display the linked page by this Target property settings. Target property has four possible values those are _blank, _parent, _self, and _top. The _blank value displays the destination page in a new window without frames. The _parent shows the linked page in the immediate frameset parent. The _self shows the page in frame with focus and the _top show the linked page in the full window without frames.
We can use a tilde(~) wildcard to specify the application root. It is very useful to set HyperLink NavigateUrl property value. So we don't need to hardcode a directory name into the application's relative URL.
We can set the hyperlink control's properties programmatically at run time such as NavigateUrl, Text, and ImageUrl. The main advantage of hyperlink server control is that we can set link properties in server code. As an example, we can dynamically change the text and destination URL of a link. We can data bind hyperlink control to specify the target URL. To create data-bound hyperlink controls, we can add them as children of Repeater, DataList, DetailsView, GridView, or Formview control. HyperLink does not raise a click event in the server code when someone clicks the link.
The following c# example source code demonstrates to us how can we use hyperlink web server control in asp.net. It also shows the declarative syntax of hyperlink control.
<%@ Page Language="C#" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net HyperLink example: how to use</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">HyperLink example</h2>
<asp:HyperLink
ID="HyperLink1"
runat="server"
Text="Visit Flying Crow Page"
NavigateUrl="~/FlyingCrow.aspx"
>
</asp:HyperLink>
<br />
<asp:HyperLink
ID="HyperLink2"
runat="server"
>
</asp:HyperLink>
</div>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<!DOCTYPE html">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>asp.net HyperLink example: FlyingCrow</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Navy">Flying Crow</h2>
<asp:Image
ID="Image1"
runat="server"
ImageUrl="~/Images/FlyingCrow.jpg"
BorderWidth="3"
BorderColor="SaddleBrown"
/>
</div>
</form>
</body>
</html>
How to use PlaceHolder in asp.net
PlaceHolder control does not provide any visible output. We only can see the dynamically added server controls inside a PlaceHolder control as child controls. We can add, insert and remove server controls programmatically in the PlaceHolder control.
The following asp.net c# example code demonstrates to us how can we add server controls dynamically in a web page using PlaceHolder web server control.
In the below example code, we put a PlaceHolder server control by declarative syntax. We also create a Button control with a Click event. When someone clicks the button, we create an Image control instance programmatically. After populating the Image server control we add it to the PlaceHolder control dynamically using ControlCollection class’s Add() method as the Controls Add(). The Add() method adds the specified control object to the collection.
Here controls collection is PlaceHolder child controls collection. The Add() method requires an argument. This argument type is System.Web.UI.Control. The new control is added to the end of an ordinal index array. To add a new control to a specific index position we can use AddAt() method. Finally, the web page displays the image that is dynamically added to the page using PlaceHolder server control.
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Image img = new Image();
img.ImageUrl = @"~/Images/sea.jpg";
img.BorderWidth = 3;
img.BorderColor = System.Drawing.Color.SaddleBrown;
PlaceHolder1.Controls.Add(img);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net PlaceHolder example: how to use</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Navy">PlaceHolder Example</h2>
<asp:PlaceHolder
ID="PlaceHolder1"
runat="server"
>
</asp:PlaceHolder>
<br />
<asp:Button
ID="Button1"
runat="server"
Text="Add Image Control"
OnClick="Button1_Click"
Font-Bold="true"
ForeColor="SaddleBrown"
/>
</div>
</form>
</body>
</html>
ASP.NET RegularExpressionValidator - Validate U.S. Social Security Number
The following asp.net c# tutorial code demonstrates how we can validate a US Social Security Number. We used a RegularExpressionValidator control and a RequiredFiledValidator control to validate a specified United States Social Security Number.
A RegularExpressionValidator control checks whether the value of an input control (as an example a TextBox) matches a pattern defined by a regular expression. The regular expression validation allows the asp.net c# developers to check for predictable sequences of characters, such as those in Zip Codes, telephone numbers, and emails.
But there is an issue while validating using RegularExpressionValidator control. If the specified input control is left empty the regular expression validation will succeed. So, when a value is required for the associated input control (as an example TextBox), the asp.net c# developers have to use a RequiredFieldValidator in addition to the RegularExpressionValidator.
The ValidationExpression is an important property in RegularExpressionValidator control. The ValidationExpression property allows the asp.net developers to get or set the regular expression that determines the pattern used to validate an input field (as an example a TextBox).
The ValidationExpression property value is a String. This String specifies the regular expression used to validate an input field for format. The default value of the ValidationExpression property is Empty. The ValidationExpression property throws HttpException if the regular expression is not properly formed.
So finally, the asp.net c# developers can use a RegularExpressionValidator control to validate a US Social Security Number. To validate that, The developers just have to pass the specified regular expression to the ValidationExpression property of RegularExpressionValidator control. They also have to associate a RequiredFieldValidator control to make the input control required.
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, System.EventArgs e)
{
if(!this.IsPostBack)
{
Label1.Font.Bold = true;
Label1.Font.Italic = true;
Label1.Font.Size = FontUnit.Large;
Label1.ForeColor = System.Drawing.Color.Crimson;
TextBox1.BackColor = System.Drawing.Color.SlateBlue;
TextBox1.ForeColor = System.Drawing.Color.AliceBlue;
Button1.Font.Bold = true;
Button1.ForeColor = System.Drawing.Color.SlateBlue;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Your Social Security Number: " + TextBox1.Text.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net RegularExpressionValidator: how to validate U.S. Social Security Number</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Navy">RegularExpressionValidator<br /><i>U.S. Social Security Number</i></h2>
<asp:Label
ID="Label1"
runat="server"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="U.S. Social Security Number"
Font-Bold="true"
ForeColor="SlateBlue"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
>
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="TextBox1"
Text="*"
>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server"
ValidationExpression="\d{3}-\d{2}-\d{4}"
ControlToValidate="TextBox1"
ErrorMessage="Input valid U.S. Social Security Number!"
></asp:RegularExpressionValidator>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Text="Submit U.S. Social Security Number"
OnClick="Button1_Click"
/>
</div>
</form>
</body>
</html>
ASP.NET RegularExpressionValidator - Validate U.S. Phone Number
The following asp.net c# tutorial code demonstrates how we can validate a US Phone Number. In the below example, we validated a United States Phone Number by using a RegularExpressionValidator control.
The RegularExpressionValidator control checks whether the value of an input control (such as a TextBox) matches a pattern defined by a regular expression. Regular expression validation allows the asp.net c# developers to check for predictable sequences of characters, such as those in Zip Codes, telephone numbers, and URLs.
When the input control (such as a TextBox) is empty, the regular expression validation will succeed. So, if a value is required for the associated input control (such as a TextBox), the asp.net c# developers have to use a RequiredFieldValidator in addition to the RegularExpressionValidator web server control.
The RegularExpressionValidator ValidationExpression property allows the asp.net developers to get or set the regular expression that determines the pattern used to validate an input field (such as a TextBox). The ValidationExpression property value is a String that specifies the regular expression used to validate an input field for format. The default value of this property is Empty. The ValidationExpression property throws HttpException if the regular expression is not properly formed.
So finally, with a RegularExpressionValidator control, the asp.net c# developers can validate a US Phone Number. The developers just have to pass the specified regular expression to the ValidationExpression property value. The asp.net developers also have to use a RequiredFieldValidator control to make the input control (such as a TextBox) required.
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, System.EventArgs e)
{
if(!this.IsPostBack)
{
Label1.Font.Bold = true;
Label1.Font.Italic = true;
Label1.Font.Size = FontUnit.Large;
Label1.ForeColor = System.Drawing.Color.SeaGreen;
TextBox1.BackColor = System.Drawing.Color.Tomato;
TextBox1.ForeColor = System.Drawing.Color.Snow;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Your Phone Number: " + TextBox1.Text.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net RegularExpressionValidator example: how to validate U.S. Phone Number</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Navy">RegularExpressionValidator: U.S. Phone Number</h2>
<asp:Label
ID="Label1"
runat="server"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="U.S. Phone Number"
Font-Bold="true"
ForeColor="DodgerBlue"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
>
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="TextBox1"
Text="*"
>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server"
ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"
ControlToValidate="TextBox1"
ErrorMessage="Input valid U.S. Phone Number!"
></asp:RegularExpressionValidator>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Text="Submit Phone Number"
Font-Bold="true"
ForeColor="DodgerBlue"
OnClick="Button1_Click"
/>
</div>
</form>
</body>
</html>
ASP.NET RegularExpressionValidator - Validate U.S. Zip Code
The following asp.net c# tutorial code demonstrates how we can validate a US Zip Code. In this example, we will validate the United States Zip Code with RegularExpressionValidator web server control.
The RegularExpressionValidator web server control checks whether the value of an input control such as TextBox matches a pattern defined by a regular expression. This type of validation allows the asp.net developers to check for predictable sequences of characters, such as those in Zip Codes, telephone numbers, and URLs.
If the input control such as TextBox is empty, the regular expression validation will succeed. So, if a value is required for the associated input control (TextBox), the asp.net developers have to use a RequiredFieldValidator web server control in addition to the RegularExpressionValidator web server control.
The RegularExpressionValidator ValidationExpression property allows us to get or set the regular expression that determines the pattern used to validate an input field such as a TextBox. The ValidationExpression property value is a String that specifies the regular expression used to validate an input field for format. The default value of this property is Empty. The ValidationExpression property throws HttpException if the regular expression is not properly formed.
So finally, using RegularExpressionValidator control the asp.net c# developers can validate a US Zip Code. They just have to pass the specified regular expression to the ValidationExpression property value. The developers also have to use a RequiredFieldValidator control to make the input TextBox control required.
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, System.EventArgs e)
{
if(!this.IsPostBack)
{
Label1.Font.Bold = true;
Label1.Font.Italic = true;
Label1.Font.Size = FontUnit.Large;
Label1.ForeColor = System.Drawing.Color.HotPink;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Your Zip Code: " + TextBox1.Text.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net RegularExpressionValidator example: how to validate U.S. Zip Code</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Teal">RegularExpressionValidator: U.S. Zip Code</h2>
<asp:Label
ID="Label1"
runat="server"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="U.S. Zip Code"
Font-Bold="true"
ForeColor="DodgerBlue"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
BackColor="DodgerBlue"
ForeColor="AliceBlue"
>
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="TextBox1"
Text="*"
>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server"
ValidationExpression="\d{5}(-\d{4})?"
ControlToValidate="TextBox1"
ErrorMessage="Input valid U.S. Zip Code!"
></asp:RegularExpressionValidator>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Text="Submit Zip Code"
Font-Bold="true"
ForeColor="Crimson"
OnClick="Button1_Click"
/>
</div>
</form>
</body>
</html>
Validate an URL using RegularExpressionValidator in asp.net c#
The following asp.net c# tutorial code demonstrates how we can validate an URL. Here we will validate an URL by using the RegularExpressionValidator web server control.
The RegularExpressionValidator web server control checks whether the value of an input control matches a pattern defined by a regular expression. This type of validation allows asp.net developers to check for predictable sequences of characters, such as those in email addresses, telephone numbers, and URLs.
If the input control is empty, the validation will succeed. So, if a value is required for the associated input control, asp.net developers have to use a RequiredFieldValidator control in addition to the RegularExpressionValidator control.
The RegularExpressionValidator ValidationExpression property gets or sets the regular expression that determines the pattern used to validate a field. This property value is a String which specifies the regular expression used to validate a field for format. The default is Empty. The ValidationExpression throws HttpException if the regular expression is not properly formed.
So finally, using RegularExpressionValidator control the asp.net c# developers can validate an URL. They just have to pass the specified regular expression to the ValidationExpression property value. The developers also have to use a RequiredFieldValidator control to make the input control required.
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Your Home Page:<br/ >" + TextBox1.Text.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net RegularExpressionValidator example: how to validate URL</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Navy">RegularExpressionValidator: Internet URL</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Bold="true"
Font-Italic="true"
Font-Size="Large"
ForeColor="HotPink"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="Home Page"
Font-Bold="true"
ForeColor="Teal"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
BackColor="Teal"
ForeColor="Snow"
Width="250"
>
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="TextBox1"
Text="*"
>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server"
ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"
ControlToValidate="TextBox1"
ErrorMessage="Input valid Internet URL!"
></asp:RegularExpressionValidator>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Text="Submit URL"
Font-Bold="true"
ForeColor="Teal"
OnClick="Button1_Click"
/>
</div>
</form>
</body>
</html>
Validate an email address using RegularExpressionValidator in asp.net c#
The Visual Studio and visual web developer .net IDE can auto-generate RegularExpressionValidator validation expression. It is a very useful and time-saving feature of visual studio. when validation failed RegularExpressionValidator control shows a predefined error message.
This example demonstrates how can we validate user-inputted email addresses by RegularExpressionValidator. When the user inputs the email address and presses the submit button, the RegularExpressionValidator control's validation expression checks whether the inputted email is a well-formed email address or not. If it is not a valid formatted email address then validation failed and stops form submission.
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Your email: " + TextBox1.Text.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net RegularExpressionValidator example: how to validate email address</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">RegularExpressionValidator: email</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Bold="true"
Font-Italic="true"
Font-Size="Large"
ForeColor="SeaGreen"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="Email"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
BackColor="DodgerBlue"
ForeColor="AliceBlue"
>
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="TextBox1"
Text="*"
>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
ControlToValidate="TextBox1"
ErrorMessage="Input valid email address!"
>
</asp:RegularExpressionValidator>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Text="Submit email"
Font-Bold="true"
ForeColor="DodgerBlue"
OnClick="Button1_Click"
/>
</div>
</form>
</body>
</html>