Facebook Goes Live with Bookmark Prompt

A couple of months ago, Facebook announced some ambitious changes to their API. We’re now starting to see some of the first of the newly announced features be released into the wild. A couple of weeks ago, Facebook added the ability for developers to ask prompt to bookmark their application. Previously, users were only able to add bookmarks using the “Add Bookmark” in Facebook’s taskbar.

Facebook’s Developer Wiki says that applications should only launch the prompt after a user clicks on a link, but it’s likely that those guidelines will be abused.

Here’s what the prompt looks like for the “Spay Day Online Pet Photo Contest” application that Factor 360 developed for the Humane Society of the United States:

bookmark:

Here’s how to load the prompt on an Facebook Application (Iframe) using XFBML:

First, you’ll want to make sure that you have the prerequisites ready so that you can use XFBML.

Then, make a hyperlink that calls an “AddBookmark” function that we’ll write. You could also do a submit button or anything else that would call a JavaScript function.

Remember to <a href=”#” onclick=”AddBookmark(); return false;”>Bookmark this Application!</a>

Then, use the following JavaScript to define the AddBookmark function.

<script type=”text/javascript”>
function AddBookmark() {
FB_RequireFeatures(["Connect"], function() {
FB.Facebook.init(’APIKEY’, ‘xd_receiver.htm’);
FB.ensureInit(function() {
FB.Connect.showBookmarkDialog(callback);
});
});
}
function callback(post_id, exception) {
alert(’bookmarked’);
}
</script>

Make sure to replace “API Key” with your application’s API Key. The “FB.ensureinit” function makes sure that the library has fully loaded before trying to execute it. The reference to “FB.Connect.showBookmarkDialog(callback);” is where the magic happens. the callback function occurs after the user has closed the dialog box. You could put just about anything you want in here. For this demonstration, I’ve just included a basic JavaScript alert.

In the next couple of months, Facebook will be launching a number of additional API changes, including the removal of classic application invites and the addition of sending messages Facebook’s Inbox from within Applications. Developers will also soon be able to get access to their user’s email address if they give permission. You can see other changes coming on Facebook’s Developer Roadmap.



Uncategorized

How to Build a Code Igniter Development and Testing Environment on Windows

I’ve been playing around with the Code Igniter Framework for PHP over the last couple of weeks, primarily because Net Tuts has a series of 6 high-quality screencasts showing off some basic functionality of the framework. Essentially, Code Igniter provides some additional functionality and provides a standardized means of creating pages and methods using the MVC framework. If you’re not used to MVC, it’s a bit of an adjustment, but it can have some benefits on the testing side of things.

If you plan on doing any Code Igniter work, you’re going to need some form of development environment for it. On the Net Tuts tutorial, the author uses Text Mate, which works pretty well as a Mac product, but I’ve found that PHP Eclipse is a bit better of a solution as a development environment on the windows side. You’ll also need to get a copy of WAMP setup, get the CodeIgniter files and configure CodeIgniter to look at the right path on your web-server as well as the correct database.

Here’s how to setup the ultimate development and test environment for Code Igniter in Windows

Step 1: Installing Wamp

The first thing you’ll need to do is get a copy of WAMP. This stands for “Windows Apache MySQL and PHP”. It essentially provides a set of web-development framework that combines all of the tools that you need for creating a PHP test-bed in a Windows environment. Since Joomla is based on PHP, WAMP is a perfect solution to run Joomla on top of. You can download the installation files from WampServer.com

You will also be asked about SMTP information. Unless you have a specific need to do anything that involves sending emails from your web-server, it’s safe to leave those blank. If you are developing contact forms or somethign that would require credentials, you can get those from your internet service provider.

Step 2: Testing WAMP

After getting WAMP installed, you’ll be given the option of letting it start up automatically or you can simply launch WAMP from the start menu. Once you have the WAMP client running, you can enable the web-server and database by right clicking on the icon and clicking “Start All Services”. To make sure that the environment is working properly, right click the icon and select “Local Host.”  If all is well, you’ll see a page that says “WAMPServer” that has a white-background.

wamp-first-steps

Step 3: Getting Code Igniter

Once you have WAMP running, you’ll want to grab a copy of the Code Ingiter files from the Code Igniter Website. They typically come in the form of a ZIP file. Take the files in the Zip File and extract them to a sub directory of your WAMP installation’s WWW directory. Typically WAMP’s WWW directory is located at “c:\wamp\www\”, so a good directory to put your files in might be c:\wamp\www\ci\”.

Step 4: Testing Code Igniter

The next thing that you want to do is to test out your copy of Code Igniter on WAMP and make sure that it’s running properly. You can do this by opening up your web-browser and navigating to “http://localhost/ci/” (assuming that you named your Code Igniter file “ci”). If it’s working, it should look like this:

code igniter welcome

Step 5: Configuring Code Igniter

Once you have code igniter working, you’ll want to make a few modifications to Code Igniter’s config file so that Code Igniter is properly configured and can access your database.

The first file  you want to modify is “config.php”, this is located in “/system/application/config/” relative to your root directory of code igniter, for us, that would be “C:\wamp\www\ci\system\application\config.”

On line 14, you’ll notice:

$config['base_url']    = “http://example.com/”;

We’ll want to change that URL to the URL of our code igniter install, so it should be:

$config['base_url']    = “http://localhost/ci”;

Step 6: Database Configuration

Finally, we’ll want to point Code Igniter at a database if we want to use one. Code Igniter by it self does not require a database, but if you want to do a project that requires database access, WAMP comes with MySQL Server, which will work just fine for a development environment.

To connect Code Igniter to a database, you’ll want to look at lines 40-43 of “database.php”, which is also located in Code Igniter’s config directory. We need to setup a username and password and choose which database we want to make use of. WAMP’s default MySQL username and password is “root” and nothing, so enter those in for your local environment. You’ll also want to make sure that your host name is set to localhost and that your database name is set to the database that you create.

$db['default']['hostname'] = “localhost”;
$db['default']['username'] = “root”;
$db['default']['password'] = “”;
$db['default']['database'] = “DATABASENAMEHERE”;

Step 7: Choosing an Editor

Right now, you have everything you need to start developing in Code Igniter, but you’re probably going to want some form of editor that will make your life a lot easier. The one I like to use is PHP Eclipse, which can be download from eclipse.org. Other editors you might want to try include TextPad, and TextMate.

Step 8: Making Your First Program

Now that your development and hosting environment is ready to go, you can start writing some code. To write your first “Hello World” program, head on over to Net Tuts and watch “CodeIgniter From Scratch: Day 1“.

Uncategorized

How to Post to Facebook’s “Stream” using Facebook Connect and XFBML

For my day job, I’ve been developing a facebook application to coincide with its annual SpayDay event. Developing the application has caused several headaches, but once I realized that the majority of the facebook integration wouldn’t happen from the Facebook Developer Toolkit (an ASP.NET Facebook Development Framework), and instead from JavaScript-based XFBML, life got a lot easier. Specifically, the application that I’m developing is an ASP.NET-based iframe application, which probably isn’t the best choice for a facebook application, but it’s what I’m familiar with, so it works.

Facebook recently announced that they are streamlining their primary integration points to the stream (users’ facebook wall posts) and to the inbox. As of writing this article, the inbox API isn’t out yet, but the StreamPublish function (the function that everyone is supposed to use to write to people’s streams and facebook walls), has been out for a while. For the purpose of this demonstration, we’ll be writing an XFBML function using FacebookConnect. Typically this would apply to IFrame Applications on Facebook.

Here’s how to implement posting to a Facebook user’s wall/stream using Facebook Connect.

First, there some prerequisites to place on your page before you can use XFMBL. Basically, it’s a couple of scripts that you need to reference which process the FBML and pass data back and forth to Facebook using a cross-domain receiver. You can learn how to add those scripts to your page here.

The next thing to do is to write a function that will call the XFBML, which will look something like this. Note that the specific text I used is for the SpayDay application, but it’s pretty easy to start making modifications to specific parts of the post.

    <script type="text/javascript">

        //post story function
        function PostStory() {

            //init facebook
            FB_RequireFeatures(["Connect"], function() {

                FB.Facebook.init('PLACE_YOUR_API_KEY_HERE', 'xd_receiver.htm');

                FB.ensureInit(function() {

                    var message = 'I support Bill The Aircraft Carrier in the SpayDay Online Photo Contest! Will you vote for Bill The Aircraft Carrier?';
                    var attachment = {
                        'name': 'Vote for Bill The Aircraft Carrier!',
                        'href': 'http://spayday.factor360.com/contest.html?page=viewInd&id=48082&contestId=2', 'caption': '{*actor*} supports Bill The Aircraft Carrier in the SpayDay Online Photo Contest!',
                        'description': 'Bill The Aircraft Carrier`s favorite thing to do is fight the Klingons, but sometimes gets in trouble because he/she likes to fight the Klingons. Bill The Aircraft Carrier makes me smile because... he has spock-like ears.',
                        "media": [{ "type": "image", "src": "http://spayday.factor360.com/calendar_contest/images/69839_1.jpg", "href": "http://spayday.factor360.com/contest.html?page=viewInd&id=48082&contestId=2"}]
                    };
                    var action_links = [{ 'text': 'Vote for Bill The Aircraft Carrier!', 'href': 'http://spayday.factor360.com/contest.html?page=viewInd&id=48082&contestId=2'}];
                    FB.Connect.streamPublish(message, attachment, action_links, null, "Share your support for Bill The Aircraft Carrier!", callback, false, null);
                });
            });
            function callback(post_id, exception) {
                alert('Wall Post Complete');
            }

}

</script>

A Few Notes:

Now that we have our function written, we simply need to call it. You can use hat with a plain old hyperlink:

<a href=’#onclick=‘PostStory(); return false;’>Post a story!</a>

That’s pretty much it. Once you get the hang of a few different XFBML functions, the rest come pretty easily. You should see something like this if all is well with your code:

post

One debugging hint. If nothing pops up at wall and you can’t get ANY XFBML to work, make sure to set your Facebook Connect URL to the same URL as your Facebook Application in your Application’s settings in the Developer Application.

Facebook

Fast and Efficient C# and Visual Basic String Concatenation

If you do any sort of web development work on the .NET platform, you are going to find yourself concatenating (connecting) strings together on a very regular basis. There are two ways to do this.

The first is with a traditional string concatenation, which would look something like this:

string MyString = String.Empty;
MyString = “Hello ” + “World”;

The second way, is using the StringBuilder library, which would look something like this:

StringBuilder MyString = new StringBuilder();
MyString.Append(”Hello “);
MyString.Append(”World”);

These two sets of code do basically the same thing, but is it preferable to use one over the other? It turns out, that the StringBuilder class is much, much more efficient when dealing with large sets of strings. For short strings, with fewer than five concatenations, chances are you’ll be better off with traditional string concatenation because you don’t have to instantiate a copy of the StringBuilder library, but for situations that you want to do a lot of string manipulation, you definitely want to use the StringBuilder library.

Here’s a synthetic test using C# and ASP.NET comparing the two:

        Trace.IsEnabled = true;

        StringBuilder StBuilder = new StringBuilder();
        Trace.Write(”String Builder Append Begin”);
        for (int x = 0; x < 10000; x++)
        {
            StBuilder.Append(”Testing123″);
        }
        Trace.Write(”String Builder Complete”);

        string stString = String.Empty;
        Trace.Write(”String Concatenation Beginning”);
        for (int x = 0; x < 10000; x++)
        {
            stString += “Testing123″;
        }
        Trace.Write(”String Concatenation Complete”);

The test concatenated the string 10,000 times. Although it’s a synthetic test, it shows that the StringBuilder class is substantially more efficient than the string class for concatenation. The string class concatenated the text in 5.292587 seconds. The StringBuilder class performed the same task in just 0.006142 seconds. In other words, the StringBuilder was over 850 times faster at concatenating the string than the string class was.

Now that’s a performance benefit!

ASP.NET, C#

ASP.NET Performance Tip: Remove Unnecessary Library References

Over the last few days, I’ve been scouring the web for techniques and strategies to optimize ASP.NET code so that it runs faster and more efficient, resulting in quicker load times. A lot of what I found was pretty standard advice, disable viewstate, use the StringBuilder for concatenation, disable tracing and use AJAX. One piece of advice that I didn’t find when searching was to be selective about the libraries that you reference.

By default, ASP.NET will add the following references to your page:

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

In a library that I was using, I was able to pair those down to these five libraries:

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

After removing the un-necessary libraries, the page load time decreased by nearly half of a second. If you were to do this with all of your libraries and pages, chances are you could see a pretty significant performance increase.

ASP.NET, C#

How to Display Your Twitter Feed using ASP.NET

As I write this article, It’s about 75 degrees and Sunny outside. When I should be going out on a bike ride, instead I’ve opted to play with Twitterizer (an ASP.NET Twitter Library). Twitterizer is an ASP.NET library that lets you interact with the Twitter API using easy to use objects and methods. It will work with any of the .NET variants (C#, VB, J#, Windows Forms, ASP.NET, WPF, etc). I added the functionality into the 360 Web Content Management System and I thought I’d share with you how I did it.

Here’s how to retrieve twitter feeds in ASP.NET

(1) Get a copy of the Twitterizer Library

First, you’ll need to get a copy of the Twitterizer Library from Google’s Codebase. The download is pretty small and contains only the application library (DLL) you need. Create a new website in ASP.NET and extract the twitterizer library to the /bin/ folder so that you can use it.  Once you have it placed in your /bin/ folder, add a “using” reference to the library in the header of your page.

using Twitterizer.Framework;

(2) Create a “Twitter” object and Retrieve Your Status Updates.

The library contains a few different objects that you can create. A “Twitter” object is the most generic object that you can create. Creating an instance of this object using your username and password gives you all the functionality you would normally have in Twitter, but instead of using the Twitter web interface, you’re using C# or Visual Basic. First, we’ll need to instantiate the object, and then get a collection of status updates from your account.

Twitter thisUser = new Twitter(”UserNameHere”, “PasswordHere”);
TwitterStatusCollection thisCollection = thisUser.Status.UserTimeline();

(3) Loop Through Your Status Updates and Generate Some HTML

The “TwitterStatusCollection” object type is a list of “TwitterStatus” objects, so you can use a foreach loop and go through your most recent status updates. You’ll notice in the code below that I also do some basic work with the time of the status update to generate a hyperlink to the page of the status, similar to what Twitter does.

string TwitterCode = “”;
foreach (TwitterStatus thisStatus in thisCollection)
{

TimeSpan thisSpan = new TimeSpan();
thisSpan = DateTime.Now.Subtract(thisStatus.Created);

string TimeBetween = “”;
if (thisSpan.Days > 0) { TimeBetween = thisSpan.Days.ToString() + ” days ago”; }
else if (thisSpan.Hours > 0) { TimeBetween = thisSpan.Days.ToString() + ” hours ago”;}
else if (thisSpan.Minutes > 0) { TimeBetween = thisSpan.Days.ToString() + ” minutes ago”;}
else if (thisSpan.Seconds > 0) { TimeBetween = thisSpan.Days.ToString() + ” seconds ago”;}

TwitterCode += “<div class=’TwitterStatus’>” + thisStatus.Text + ” <a href=’http://twitter.com/” + thisStatus.TwitterUser.UserName + “/status/” + thisStatus.ID + “‘>” + TimeBetween + “</a></div>”;
}
(4) Display Your Tweets

You now have a string with your most recent twitter status updates that you can display on the page using a simple Response.Write() or you can display it in a label. You can see a variation of this code running on the “Twitter” page for the 360 Web Content Management System.

You can also download a copy of my sample code.

ASP.NET, C#, Content Management Systems, Social Media, Visual Basic

How to Implement an ASP.NET Color Picker

One of the components of the 360 Web Content Management System (website in progress) that I wanted to develop was an events calendar that allowed you to post events into color-coded categories. You can see a demo of it here. At first, I had it so that users would manually enter in a 6-character HTML color code, but it was very non-intuitive for anyone who’s never worked with HTML before. Eventually I stumbled upon the ASP.NET Color Picker control. It’s a custom ASP.NET control that you can add to a page much in the way that you can add a text box, radio buttons, or a drop down list.

Here’s how to implement the ASP.NET Color Picker Control

(1) Download the library and add it to your project

First, download the library from the ASP.NET Color Picker Control website. Make sure to download the latest binary release from the website. Currently that version is ASP.NET Color Picker v.1.4.10423.1 Binary. Once you get the zip file, it will contain a library that you should extract to the /bin/ folder of your website.

(2) Register the library on your page

ASP.NET provides a set of standard controls that you can add to a page that start with the “ASP” prefix, such as “<ASP:TextBox runat=”server” id=”txtBox” />. Any custom controls will have their own prefix that you specify by registering the library on the page. It’s another line of code that you add to the top of the page next to your page definition. It should look something like this:

<%@ Register Assembly=”Karpach.WebControls” Namespace=”Karpach.WebControls” TagPrefix=”cc1″ %>

(3) Add the control to your page

Now that you have the library referenced, you can add the control to your page and make use of it.  For the purpose of this demo, I’m going to set the AutoPostBack property to true and run a function whenever the color is changed. This will show us the color that we picked inside of a label (also shown below) after we select a new color.

<cc1:ColorPicker ID=”colorBackgroundColor” runat=”server” AutoPostBack=”true” OnColorChanged=”chngColor” />
<br /><br />
<asp:Label ID=”lblResults” runat=”server” Text=”"></asp:Label>

(4) Create Your C# Function

After we choose a color, we have to do something with it. With the ColorPicker control above, I’m using the OnColorChanged property to call the “chngColor” function, which in C# will look something like this. This will also demonstrate how to programmatically read the color chosen with the .Color property of the ASP.NET Color Picker Control

protected void chngColor(object sender, EventArgs e)
{
lblResults.Text = “<div style=’background-color:#” + colorBackgroundColor.Color.Replace(”#”, “”) + “;height:50px;width:80px;text-align:center;padding-top:35px;’>Sample Text</div>”;
}

(5) Success

So far, we’ve added the library to our project, registered the library on the page, added the control to the page, and done something with the color chosen by the user. Your page should look something like this:

color-picker

You can download my sample program here.

360 WebCMS, ASP.NET, C#, Content Management Systems, Database, JavaScript, Security, Visual Basic

How to Validate Email Addresses in C#

I was recently doing doing support for a client that had a newsletter system. The previous employee had neglected to do much in the form of format validation for email addresses from both a user-input standpoint and system-integrity standpoint. Since there were several email addresses in the database that didn’t meet the basic conventions of an email address, the user received the following error whenever she tried to send out a message:

Exception Details: System.FormatException: The specified string is not in the form required for an e-mail address.

Ouch. To remedy this issue, I added a check to make sure the email address was valid before it attempted to send the message. In the code below, I’m making use of the System.Text.RegularExpressions library that comes with the .NET framework. The code below is written in C# but the code will be very similar in Visual Basic. It will also work in ASP.NET, WPF or plain old windows forms.

Here’s a C# function that will determine whether or not an email address is valid:

public static bool IsValidEmail(string strEmailAddress)
{
if (strEmailAddress == null)
{
return false;
}
else
{
return System.Text.RegularExpressions.Regex.IsMatch(strEmailAddress, @"^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\.(com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|[a-zA-Z]{2})$", RegexOptions.IgnorePatternWhitespace);
}
}

I also made some modifications to the system on the front-end, so when a user registered from then on, that it would validate that they have entered an email address and that the email address matched the format of an email address using a RequiredFieldValidator and a RegularExpressionValidator.<–>

ASP.NET, C#, Security, Visual Basic

Create a Sortable HTML Table with JQuery and TableSorter

One of the more useful features of ASP.NET’s GridView control is that users can sort the information in the table they are seeing by any number of fields. To allow this sorting to happen, ASP.NET sends a post-back to the server and the web server re-renders the page with the GridView re-sorted in the order requested. Now, there’s a way to display a table that can be sorted by any number of fields using only JavaScript. There’s no communication back and forth with the web-server wasting bandwidth and processing power on the web-server.

The JQuery library that allows this to happen is called Tablesorter. Tablesorter has a ton of very useful features, including having a very small code base, the ability to sort across multiple columns and is compatible with just about every web-browser that’s currently being used, even IE 6. It has sort parsers for a number of types of formats, including text, URIs, integers, currency, floats, IP addresses and dates, so whatever type of data you have in the table, chances are it will be able to intelligently sort it.

Here’s how to create a sortable table with TableSorter and JQuery

(1) Get the required libraries and reference them.

You’ll want to download the minfiied version of Tablesorter from the Tablesorter website. The slimmed-down version comes in at 12 KB. You can download that here. You’ll also want to get a copy of the latest version of JQuery which is available form the JQuery Website. Once you get those two files downloaded, you’ll want to add references to them in your page’s <HEAD>. They should look something like this depending on where you placed your files:

<script src=”jquery.tablesorter.min.js” type=”text/javascript”></script>
<script src=”jquery-1.3.2.min.js” type=”text/javascript”></script>

(2) Make an HTML Table

Here’s a demonstration table that the Tablesorter website provides for us to use. Simply add this to the body of your page:

<table id="myTable">
<thead>
<tr>
    <th>Last Name</th>
    <th>First Name</th>
    <th>Email</th>
    <th>Due</th>
    <th>Web Site</th>
</tr>
</thead>
<tbody>
<tr>
    <td>Smith</td>
    <td>John</td>
    <td>jsmith@gmail.com</td>
    <td>$50.00</td>
    <td>http://www.jsmith.com</td>
</tr>
<tr>
    <td>Bach</td>
    <td>Frank</td>
    <td>fbach@yahoo.com</td>
    <td>$50.00</td>
    <td>http://www.frank.com</td>
</tr>
<tr>
    <td>Doe</td>
    <td>Jason</td>
    <td>jdoe@hotmail.com</td>
    <td>$100.00</td>
    <td>http://www.jdoe.com</td>
</tr>
<tr>
    <td>Conway</td>
    <td>Tim</td>
    <td>tconway@earthlink.net</td>
    <td>$50.00</td>
    <td>http://www.timconway.com</td>
</tr>
</tbody>
</table>

(3) Sort Your Table

The only thing left to do to make our quick and dirty demo of the table sorter to work is to call the sorting library using the document.ready() function that’s frequently used with JQuery. That will look something like this:

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

$(document).ready(function()
{
$(”#myTable”).tablesorter();
}
);

</script>

(4) Further Development

The next logical step is to add some CSS formatting that will give the user a better idea of which sort direction they’re doing. You can see a demo of how to style the different sort directions on the Tablesorter website, which would be a must on any production site. You might also want to play around with doing multi-column sorts and with their widget system.

Click here to download my example code (24 KB).

JQuery, JavaScript

How to Validate Forms with JQuery

Just about everyone who’s ever made a web-application knows that you generally can’t trust your users to enter data correctly into a form. Some of them will ignore important fields, others will type in data that couldn’t possibly be right. Some will try to choose two character passwords and others will enter in a long string of text when all you wanted to do was get their age in the form of numbers.

A lot of these errors can be mitigated by using the right input controls. You want to use the right HTML input control for the right situation.. You certainly wouldn’t want to use a textbox to have someone enter in their gender and you definitely don’t want to use a drop down list to have someone enter their email address. Although using the right input controls for the right questions takes a long way in helping ensure that we get good data, that alone isn’t enough.

When it comes to textboxes, you’ll often want to make sure whatever they type in meets a specific format, such as a phone-number or an email address. You might also want to make surethey actually do type -something- in, or make sure that they type the same thing in two fields if you want to confirm that something’s accurate.

Microsoft does a pretty good job of making this happen in ASP.NET with their validation controls. More often than not, the validation controls will simply generate some javascript to perform the validation, but there’s also an option to have it validate at the server-side level. If you’d like to have a bit more control over your validators there’s some code in JQuery that we can use to make sure users what enter in good data.

The example code I’m going to demonstrate today is based off the JQuery Validate plugin.

Here’s How to Validate  Text Boxes with JQuery

(1) Download and Reference JQuery and the JQuery Validation Library

You’ll need a copy of JQuery 1.2.6+ on your system, which can be downloaded from Google.You’ll also need a copy of the JQuery Validation library, available from bassistance.de. Once you get your two libraries download, you can extract the minified version of both of them into a folder, create a new HTML page and add your header references that should look something like this:

<script src=”jquery.js” type=”text/javascript”></script>
<script src=”jquery.validate.min.js” type=”text/javascript”></script>

(2) Building your form

For this example, we’ll make a basic contact form that requires the person to enter their name, their email address and some comments. All of the fields will be required and we will also make sure that the user’s email address was entered in the correct format.

Here’s what the form will look like:

<form class=”cmxform” id=”commentForm” method=”get” action=”">
<fieldset>
<p>
<label for=”cname”>Name</label>
<em>*</em><input id=”cname” name=”name” size=”25″ class=”required” minlength=”2″ />
</p>
<p>
<label for=”cemail”>E-Mail Address</label>
<em>*</em><input id=”cemail” name=”email” size=”25″  class=”required email” />
</p>
<p>
<label for=”ccomment”>Comments:</label>
<em>*</em><textarea id=”ccomment” name=”comment” cols=”22″  class=”required”></textarea>
</p>
<p>
<input class=”submit” type=”submit” value=”Submit”/>
</p>
</fieldset>
</form>

There are a few things to note about this form. First, that all of the inputs have been given a class of “required”. This is how the JQuery library will know whether or not to validate them. If you don’t want a field to be required, simply leave it out. You’ll also note on the “E-Mail Address” field, that it has a class of class=”required email”, this will let the function know that what the user enters in also has to be a valid email address.

(3) Calling the Validation Method

Finally, we need to invoke the validation method when the page loads. We can do this with the $(document).ready() function like this:

<script>
$(document).ready(function(){
$(”#commentForm”).validate();
});
</script>

If you give you form a different ID, make sure that the ID of the form matches what you’re calling in your onLoad function.

(4) The Results

If all is well with your code, you should end up with something like this after clicking the submit button:

form

You can download my example code here. You can also download the full JQuery Validation Library with some more advanced examples.

JQuery