Saturday, March 14, 2009

Check UserName Availability Using XmlHttp in ASP.NET

Most email service providers like gmail, yahoo and hotmail provide live username availability checks. And this trend has been followed by other websites also. This is pretty simple in asp.net to check username availability before user submits the credentials. This saves time as well as increases user interactivity. In this article, I am going to show the simple username availability check mechanism using xmlhttp.

Fig 1: UserName availability check using xmlhttp in asp.net web page

Let's define a simple user registration page. I am just showing the two fields: username and email for demonstration. Please note that this is not a complete code snippet. And I haven't implemented any other validation, for instance there could be one for email validation.

RegisterUser.aspx (add this markup after form element)

<table cellpadding="0" cellspacing="2">

<tr>

<td>User Name:</td>

<td>

<asp:TextBox ID="txtUserName" runat="server" onkeydown="CheckUserNameAvailability();"></asp:TextBox>

<asp:Label ID="lblMsg" runat="server"></asp:Label>

</td>

</tr>

<tr>

<td>Email:</td>

<td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>

</tr>

<tr>

<td></td>

<td><asp:Button ID="btnRegister" runat="server" Text="Register" /></td>

</tr>

</table>

Now we add the required xmlhttp snippet in the page. This code is to be added before head section of RegisterUser.aspx page.



<script type = "text/javascript">

var xmlhttp;

function CheckUserNameAvailability()

{

xmlhttp=null;

var username=document.getElementById('<%=txtUserName.ClientID %>').value;

if(username="" || username.length<4)

{

document.getElementById("<%=lblMsg.ClientID%>").innerHTML="";

return false;

}



if (window.XMLHttpRequest)

{

// code for all new browsers

xmlhttp=new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

// code for IE5 and IE6xmlhttp=

new ActiveXObject("Microsoft.XMLHTTP");

}

if (xmlhttp!=null)

{

xmlhttp.onreadystatechange=state_Change;

xmlhttp.open("GET","CheckUserNameAvailabilityUsingJquery.aspx?UserName="+username,true);

xmlhttp.send(null);

}

else

{

alert("Oops..Your browser does not support XMLHTTP.");

}

}



function state_Change()

{

if (xmlhttp.readyState==4)

{

// 4 = “loaded”

if (xmlhttp.status==200)

{

//request was successful

//check if username is available and message

var lblMesg = document.getElementById("<%=lblMsg.ClientID%>");

if(xmlhttp.responseText=="True")

{

lblMesg.style.color="Green";

lblMesg.innerHTML="Username available.";

}

else

{

lblMesg.innerHTML="Username already in use.";

lblMesg.style.color="Red";

}

}

else

{

alert("Oops..username availability could not be checked.");

}

}

}

</script>

Here goes the page that checks if the username already exists in the database and returns true (if the username does not exists) or false (if the username is already in use).


CheckUserAvailabilityUsingXMLHTTP.aspx

//page load event
protected void Page_Load(object sender, EventArgs e)
{
CheckUserNameAvailability();
}

//checks if the username is available
//for demo, usename has been checked against the asp.net membership system
public void CheckUserNameAvailability()
{
if (Request.Params.Get("UserName") != null)
{
string username = Request.Params.Get("username");
string result = "False";
MembershipUser user = Membership.GetUser(username);
if (user != null)
{
result = "False";
}
else
{
result = "True";
}

Response.Clear();
Response.Write(result);
Response.End();
}
}

Please note the CheckUserNameAvailability.aspx page being called by the xmlhttp code in RegisterUser.aspx page. That's it. Happy Programming!

kick it on DotNetKicks.com  Shout it

Wednesday, March 11, 2009

Watermark Asp.NET Textbox Using JavaScript

Noticed the watermark implemented in custom google search TextBox, like one in the right side of this page (under heading Search asp.net, C#, oracle, SQL Server related tips and solutions)? I am showing the simple and meaningful watermark implementation of a textbox in asp.net web page in this tipsticle (tips + article).

Truly saying, every time I come across a web page, I do naturally look for the searching textbox in the website. And I do usually find it in the left corner or the right upper corner of the website. Not all the search textboxes implement the watermark but they may initialize the text in the search textbox like your search text here or just search. And my enthusiasm always inspires me to click once and then just click out the textbox to see if watermark has been implemented. In my opinion, it is good to implement watermark for the sake of user-interactivity of a website. (And let me praise facebook homepage for this!)

Ok, lets start out with a search textbox in an asp.net web page.


Now we add a javascript code snippet in the page.



function WatermarkFocus(txtElem, strWatermark) {
if (txtElem.value == strWatermark) txtElem.value = '';
}
function WatermarkBlur(txtElem, strWatermark) {
if (txtElem.value == '') txtElem.value = strWatermark;
}

Now is the time to add onblur and onfocus properties to the asp.net TextBox, referencing the relevant javascript function.

string strWatermarkSearch = "Search";
txtSimpleSearch.Text = strWatermarkSearch;
txtSimpleSearch.Attributes.Add("onfocus", "WatermarkFocus(this, '" + strWatermarkSearch + "');");
txtSimpleSearch.Attributes.Add("onblur", "WatermarkBlur(this, '" + strWatermarkSearch + "');");

We can see the perfect watermark implementation with our search textbox now! Happy Programming!

Liked the post? You can share this post by submitting to dzone,digg,dotnetkicks etc. You can even leave your suggestions as the comment below.


kick it on DotNetKicks.com

Friday, March 6, 2009

Using JavaScript for Validation of Different Date Formats in Asp.NET Web Form

Most often asp.net web applications need to validate date in a form. It is not that easy to play with different format of dates at different places. Mostly the mm/dd/yyyy (alternatively, mm-dd-yyyy) format of date is used. But we may need to go dd/mm/yyyy (alternatively, dd-mm-yyyy) also, and yyyy/mm/dd (alternatively, yyyy-mm-dd) format is no exception too. This article will discuss how to validate date in all these formats using simple yet powerful javascript code snippet.


Fig 1: Using ajax calendar extender to pick date into asp.net textbox in dd-mm-yyyy format



Fig 2: Validation of the date in the textbox in dd-mm-yyyy format on form submit

Let's start with the addition of a TextBox and an ajax calendarextender in a page.


Remember, we need ajax enabled page to use the calendar extender. Note that I have set the format in the calendarextender to dd-MM-yyyy. This will put the date in the targetcontrol (here, txtPurchaseDate) in dd-mm-yyyy format. On client click of the button btnSubmit, the javascript function ValidateForm() will validate the date in the textbox. If it is not in dd-mm-yyyy format, a message will be alerted as in the figures above.

Here are the functions Validateform() and validateInputDate().

function ValidateForm()
{
if(document.getElementById("txtPurchaseDate"))
{
if(validateInputDate(document.getElementById("txtPurchaseDate").value)==false)
{
alert("Please input purchase date in the format dd-mm-yyyy.");
return false;
}
}
}



//Validates date in the format dd-mm-yyyy (e.g. 19-10-2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\-.](0[1-9]1[012])[\-.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}

Now we can change the validateInputDate() date validation function to validate other date formats. Listed below are the functions for validating different date formats.


//Validates date in the format dd/mm/yyyy (e.g. 19/10/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\/.](0[1-9]1[012])[\/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}


//Validates date in the format dd-mm-yyyy or dd/mm/yyyy (e.g. 19-10-2009 or 19/10/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\- \/.](0[1-9]1[012])[\- \/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format mm/dd/yyyy (e.g. 10/19/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])[\/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format yyyy-mm-dd or yyyy/mm/dd (e.g. 2009-10-19 or 2009/10/19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\- \/.](0[1-9]1[012])[\- \/.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format yyyy-mm-dd (e.g. 2009-10-19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\-.](0[1-9]1[012])[\-.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}


// Validates date in the format yyyy/mm/dd (e.g. 2009/10/19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\/.](0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}

Happy Programming!
Liked the post? You can kick it on DotNetKicks.com and and

Popular Posts

Recent Articles