DotNetSlackers: ASP.NET News for lazy Developers

Wednesday, August 3, 2011

How to create a Dynamic Registration Form in Aspnet

Hi friends,In this Article i would like to Explain how to create dynamic Registration form using Aspnet

First,Open the MIcrosoft visual studio 2008

Next,Create one Asp.Net Web application

Next,Open the Design page of the Default.aspx



Next,Drag and Drop one Drop down list and add two items in this drop down list.

that is,click on the properties of the Drop Down List and select items and add NewRegistration item in that

Next,come to the code page that is Default.aspx.cs and copy the following code

  1. using System;  
  2. using System.Collections;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Security;  
  8. using System.Web.UI;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Web.UI.WebControls;  
  11. using System.Web.UI.WebControls.WebParts;  
  12. using System.Xml.Linq;  
  13. using System.Data.SqlClient;  
  14.   
  15. public partial class Dynamic_controls : System.Web.UI.Page  
  16. {  
  17.     SqlConnection con;  
  18.     SqlCommand com;  
  19.   protected void Page_Load(object sender, EventArgs e)  
  20.     {  
  21.         if (IsPostBack)  
  22.         {  
  23.            Createnewaccount();                       
  24.         }  
  25.          
  26.     }  
  27.   
  28.  private void Createnewaccount()  
  29.     {  
  30.         CreateDynamicTextBoxes();  
  31.         CreateDynamicTextBoxes1();  
  32.         CreateDynamicCheckBoxes();  
  33.         CreateDynamicCheckBoxes1();  
  34.         CreateDynamicRadioButtons1();  
  35.         BindDropDownLists();  
  36.     }  
  37.   
  38. protected void CreateDynamicTextBoxes()  
  39.     {  
  40.        
  41.         int c = 1;  
  42.         TextBox[] textBoxArr = new TextBox[c];//array of textboxes  
  43.         for (int i = 0; i < c; i++)  
  44.         {  
  45.              
  46.             textBoxArr[i] = new TextBox();  
  47.             textBoxArr[i].ID = "txtBox" + i.ToString();           
  48.             PH_Name.Controls.Add(textBoxArr[i]);  
  49.             RequiredFieldValidator reqfldVal = new RequiredFieldValidator();  
  50.             reqfldVal.ID = "RequiredValidator" + i;  
  51.             reqfldVal.ControlToValidate = "txtBox" + i;  
  52.             reqfldVal.ErrorMessage = "Not Empty";  
  53.             reqfldVal.SetFocusOnError = true;  
  54.             PH_Name.Controls.Add(reqfldVal);  
  55.         }  
  56.     }  
  57.     protected void CreateDynamicTextBoxes1()  
  58.     {       
  59.         int c = 1;  
  60.         TextBox[] textBoxArr1 = new TextBox[c];//array of textboxes  
  61.         for (int i = 0; i < c; i++)  
  62.         {  
  63.   
  64.             textBoxArr1[i] = new TextBox();  
  65.             textBoxArr1[i].ID = "txtBox1" + i.ToString();  
  66.             PH_pwd.Controls.Add(textBoxArr1[i]);  
  67.             RequiredFieldValidator reqfldVal1 = new RequiredFieldValidator();  
  68.             reqfldVal1.ID = "RequiredValidator1" + i;  
  69.             reqfldVal1.ControlToValidate = "txtBox1" + i;  
  70.             reqfldVal1.ErrorMessage = "Not Empty";  
  71.             reqfldVal1.SetFocusOnError = true;  
  72.             PH_pwd.Controls.Add(reqfldVal1);  
  73.              
  74.         }  
  75.     }  
  76.     private void BindDropDownLists()  
  77.     {  
  78.         SqlDataSource sqlDS = new SqlDataSource();  
  79.         sqlDS.ConnectionString = ConfigurationManager.ConnectionStrings["SAMPLE_2"].ToString();  
  80.         sqlDS.SelectCommand = "Select countryid, country_name from countrynames";  
  81.         PH_country.Controls.Add(sqlDS);  
  82.         DropDownList ddl = new DropDownList();  
  83.         ddl.ID = "ddlrank";  
  84.         ddl.DataSource = sqlDS;  
  85.         ddl.DataTextField = "country_name";  
  86.         ddl.DataValueField = "countryid";  
  87.         PH_country.Controls.Add(ddl);  
  88.         foreach (Control ctl in PH_country.Controls)  
  89.         {  
  90.             if (ctl is DropDownList)  
  91.             {  
  92.                 (ctl as DropDownList).DataBind();  
  93.             }  
  94.         }  
  95.     }  
  96.     protected void CreateDynamicCheckBoxes()  
  97.     {  
  98.                
  99.             CheckBox chk;       
  100.             chk = new CheckBox();  
  101.             chk.ID = "chkhobbies";             
  102.             chk.Text = "savings";  
  103.             chk.AutoPostBack = false;  
  104.             PH_trans.Controls.Add(chk);             
  105.          
  106.     }   
  107.     protected void CreateDynamicCheckBoxes1()  
  108.     {  
  109.        
  110.         int c = 1;  
  111.         CheckBox[] chk = new CheckBox[c];  
  112.         for (int i = 0; i < c; i++)  
  113.         {  
  114.             chk[i] = new CheckBox();  
  115.             chk[i].ID = "chkhobbies1" + i.ToString();  
  116.             chk[i].Text = "Current";           
  117.             chk[i].AutoPostBack = false;  
  118.             PH_trans.Controls.Add(chk[i]);  
  119.         }  
  120.     }     
  121.     protected void CreateDynamicRadioButtons()  
  122.     {  
  123.             RadioButton male = new RadioButton();  
  124.             RadioButton female = new RadioButton();  
  125.             male = new RadioButton();  
  126.             female = new RadioButton();  
  127.             male.Text = "Male";  
  128.             female.Text = "Female";  
  129.             male.Checked = false;  
  130.             female.Checked = false;  
  131.             male.GroupName = "gender";  
  132.             female.GroupName = "gender";  
  133.             male.ID = "malegender" ;  
  134.             female.ID = "gender";  
  135.             male.AutoPostBack = false;  
  136.             female.AutoPostBack = false;  
  137.             PH_gender.Controls.Add(male);  
  138.             PH_gender.Controls.Add(female);  
  139.     }  
  140.     protected void CreateDynamicRadioButtons1()  
  141.     {  
  142.         RadioButtonList radio = new RadioButtonList();  
  143.         radio.ID = "rblRow";  
  144.         radio.Items.Add(new ListItem("Male"));  
  145.         radio.Items.Add(new ListItem("Female"));       
  146.         PH_gender.Controls.Add(radio);  
  147.          
  148.     }  
  149.     protected void CreateDynamicPanel()  
  150.     {  
  151.        
  152.         int c = 1;  
  153.         Panel TextPanel = new Panel();  
  154.         for (int i = 0; i < c; i++)  
  155.         {  
  156.             TextPanel.ID = "txtPanel" + i.ToString();  
  157.             PlaceHolder1.Controls.Add(TextPanel);  
  158.         }  
  159.     }  
  160.   
  161. protected void btn_submit_Click(object sender, EventArgs e)  
  162.     {  
  163.         for (int i = 0; i < 1; i++)  
  164.         {  
  165.              
  166.             string txtvalue = "txtBox" +i.ToString();  
  167.             string txtvalue1 = "txtBox1" +i.ToString();  
  168.             string ddlvalue = "ddlrank";             
  169.             string chkvalue = "chkhobbies";  
  170.             string chkvalue1 = "chkhobbies1" + i.ToString();  
  171.             string rbvalue = "rblRow" ;  
  172.              
  173.             TextBox txt = (TextBox)PlaceHolder1.FindControl(txtvalue);  
  174.             TextBox txt1 = (TextBox)PlaceHolder1.FindControl(txtvalue1);  
  175.             DropDownList Dddl=(DropDownList)PlaceHolder1.FindControl(ddlvalue);  
  176.             CheckBox Dchk=(CheckBox)PlaceHolder1.FindControl(chkvalue);  
  177.             CheckBox Dchk1 = (CheckBox)PlaceHolder1.FindControl(chkvalue1);  
  178.             RadioButtonList Drd=(RadioButtonList)PlaceHolder1.FindControl(rbvalue);  
  179.             if (txt != null )  
  180.             {  
  181.                 try  
  182.                 {  
  183.                     string strText = txt.Text;  
  184.                     string strText1 = txt1.Text;  
  185.                     string strddl = Dddl.SelectedItem.Text;  
  186.                     string strchk = Dchk.Text;  
  187.                     string strchk1 = Dchk1.Text;  
  188.                     string strrdb = Drd.Text;  
  189.                     // store your textbox value in database  
  190.                     con = new SqlConnection(ConfigurationManager.ConnectionStrings["SAMPLE_2"].ToString());  
  191.                     con.Open();  
  192.                     com = new SqlCommand("insert into Dynamic_Form(UserName,LastName,DropdownlistValue,Chksavings,Chkcurrent,Radiovalue)values('" + strText + "','" + strText1 + "','" + strddl + "','" + strchk + "','" + strchk1 + "','" + strrdb + "')", con);  
  193.                     com.ExecuteNonQuery();  
  194.                     con.Close();  
  195.                     lbl_error.Text = "Successfully Account Created ";  
  196.                      
  197.                 }  
  198.                 catch(Exception ex)  
  199.                 {  
  200.                     throw ex;  
  201.                     //lbl_error.Text = "There is a Problem while creating Account ";  
  202.                      
  203.                 }  
  204.             }  
  205.         }  
  206.     }  

Creating a Simple Registration Form in ASP.NET

This example shows how to create a very simple registration form in ASP.NET.


STEP1: Creating the Database.

The following are the basic steps on how to create a simple database in the Sql Server:

Launch Sql Server Management Studion Express and then connect
Expand the Databases folder from the Sql Server object explorer
Right click on the Databases folder and select “New Database”
From the pop up window, input the database name you like and click add
Expand the Database folder that you have just added
Right click on the Tables folder and select “New Table”
Then add the following fields below:


Note: in this demo, I set the Id to auto increment so that the id will be automatically generated for every new added row. To do this select the Column name “Id” and in the column properties set the “Identity Specification” to yes.

Then after adding all the necessary fields, name your Table the way you like. Note that in this demo I name it “tblRegistration”

STEP2: Setting up the UI.

For the simplicity of this demo, I set up the UI like below in the WebForm:


ASPX:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Sample Registration Page</title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <table class="style1">
            <tr>
                <td>
                    Full Name:</td>
                <td>
                    <asp:TextBox ID="TxtName runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Username:</td>
                <td>
                    <asp:TextBox ID="TxtUserName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Password:</td>
                <td>
                    <asp:TextBox ID="TxtPassword" runat="server" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Re Password:</td>
                <td>
                    <asp:TextBox ID="TxtRePassword" runat="server" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Address:</td>
                <td>
                    <asp:TextBox ID="TxtAddress" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Age:</td>
                <td>
                    <asp:TextBox ID="TxtAge" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Gender:</td>
                <td>
                <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
                <asp:ListItem Value="-1">Select</asp:ListItem>
                <asp:ListItem>Male</asp:ListItem>
                <asp:ListItem>Female</asp:ListItem>
                </asp:DropDownList>
                </td>
            </tr>
        </table>
   
    </div>
    <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
    </form>
</body>
</html>


As you can see, the UI is very simple. Now let’s set up the connection string.

STEP3: Setting up the Connection String

In your web.config file set up the connection string there as shown below:

  <connectionStrings>
    <add name="MyConsString" connectionString="Data Source=WPHVD185022-9O0;Initial Catalog=MyDatabase;Integrated Security=SSPI;"
   providerName="System.Data.SqlClient" />
  </connectionStrings>

Note: MyConsString is the name of the Connection String that we can use as a reference in our codes for setting the connection string later.

STEP4: Calling up the ConnectionString in our codes

Here’s the method for calling the connection string that was set up in the web.config file.

    public string GetConnectionString()
    {
        //sets the connection string from your web config file "ConnString" is the name of your Connection String
        return System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
    }

STEP5: Writing the method for inserting the data from the registration page to the database.

In this demo, we are using the ADO.NET objects for manipulating the data from the page to the database. If you are not familiar with ADO.NET then I would suggest you to refer the following link below to get started:
Here’s the code block for inserting the data to the database.

    private void ExecuteInsert(string name, string username, string password, string gender, string age, string address)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());

        string sql = "INSERT INTO tblRegistration (Name, UserName, Password, Gender, Age, Address) VALUES "
                    + " (@Name,@UserName,@Password,@Gender,@Age,@Address)";
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlParameter[] param = new SqlParameter[6];

            //param[0] = new SqlParameter("@id", SqlDbType.Int, 20);
            param[0] = new SqlParameter("@Name", SqlDbType.VarChar, 50);
            param[1] = new SqlParameter("@UserName", SqlDbType.VarChar, 50);
            param[2] = new SqlParameter("@Password", SqlDbType.VarChar, 50);
            param[3] = new SqlParameter("@Gender", SqlDbType.Char, 10);
            param[4] = new SqlParameter("@Age", SqlDbType.Int, 100);
            param[5] = new SqlParameter("@Address", SqlDbType.VarChar, 50);

            param[0].Value = name;
            param[1].Value = username;
            param[2].Value = password;
            param[3].Value = gender;
            param[4].Value = age;
            param[5].Value = address;

            for (int i = 0; i < param.Length; i++)
            {
                cmd.Parameters.Add(param[i]);
            }

            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);

        }
        finally
        {
            conn.Close();
        }
    }

STEP6: Calling the method ExecuteInsert()

You can call the method above at Button_Click event for saving the data to the database. Here’s the code block below:

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (TxtPassword.Text == TxtRePassword.Text)
        {
            //call the method to execute insert to the database
            ExecuteInsert(TxtName.Text, TxtUserName.Text, TxtPassword.Text, DropDownList1.SelectedItem.Text, TxtAge.Text, TxtAddress.Text);

            Response.Write("Record was successfully added!");

            ClearControls(Page);
        }
        else
        {
            Response.Write("Password did not match");
            TxtPassword.Focus();
        }
    }

As you can see from the above code block, we check the value of the TxtPassword and TxtRePassword to see if match. If it match then call the method ExecuteInsert else display the error message stating that the “Password did not match”.

You also noticed that we call the method ClearControls for clearing the Text fields in the page. See the code block below for the ClearControls method:

    public static void ClearControls(Control Parent)
    {
        if (Parent is TextBox)
        { (Parent as TextBox).Text = string.Empty; }
        else
        {
            foreach (Control c in Parent.Controls)
                ClearControls(c);
        }
    }

That’s it! Hope you will find this example useful!
In this article I'll show you how to build a simple, yet powerful and extensible jQuery form validation plugin
<form>
    <fieldset>
        <legend>Legend Name</legend>
        <div>
            <label for="name">Name</label>
            <input type="text" id="name" name="name">
        </div>
    </fieldset>
</form>
This is how I markup my forms. Trying to keep it as simple and semantic as possible, but adding the div to make styling easier.

Specifying input validation

In HTML4 there is no obvious way attach validation rules to an input. A few developers have been somewhat orthodox and added their own “validation” attribute.
<input type="text" id="name" name="name" validation=required email>
This is not valid HTML, but it works in all browsers, and maybe it’s better than using a valid attribute for the wrong reasons. It's up to you, but this is how I do it.

The validation object

The base validation object contains a set of methods and properties that only needs be stored in one place, but can be accessed globally. In object oriented terminology this is commonly referred to as a Singleton.
// Wrap code in an self-executing anonymous function and 
// pass jQuery into it so we can use the "$" shortcut without 
// causing potential conflicts with already existing functions.
(function($) {

    var validation = function() {

        var rules = {  // Private object

            email : {
               check: function(value) {

                   if(value) {
                       return testPattern(value,"[a-z0-9!#$%&'*+/=?^_`{|}~-]+
                                                   (?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)
                                                   *@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])
?\                                                 .)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])");
                   }
                   return true;
               },
               msg : "Enter a valid e-mail address."
            },
            required : {

               check: function(value) {

                   if(value) {
                       return true;
                   }
                   else {
                       return false;
                   }
               },
               msg : "This field is required."
            }
        }
        var testPattern = function(value, pattern) {   // Private Method

            var regExp = new RegExp(pattern,"");
            return regExp.test(value);
        }
        return { // Public methods

            addRule : function(name, rule) {

                rules[name] = rule;
            },
            getRule : function(name) {

                return rules[name];
            }
        }
    }
    //A new instance of our object in the jQuery namespace.
    $.validation = new validation();
})(jQuery); 
// Again, we're passing jQuery into the function 
// so we can use $ without potential conflicts.
The object contains a set of rules, each with a function and a message. There's also a function called "testPattern". Being defined with the var keyword makes them private and inaccessible outside the object itself.
NOTE: I've simplified the regular expressions above to make the example readable. I suggest you take a look at the expressions from the official jQuery valide plugin for the real deal.
NOTE2: Never rely on JavaScript validation alone if your sending data to a server, you'll have to do server side validation too.
Adding the object to the jQuery $ namespace is useful because now we can access it like any other jQuery object, hence, it'll be helpful later on in our plugin code.

Public methods

Instead of hard coding lots of rules, we keep it down to a minimum. We defined a method called "addRule" and made it public by wrapping it in a return statement. The concept of returning methods and properties to make them public is commonly referred to as the module pattern.

Adding additional validation rules

People can now use our method to quickly add new custom validation rules without having to modify our code.
$.validation.addRule("test",{
    check: function(value) {
        if(value != "test") {
            return false;
        }
        return true;
    },
    msg : "Must equal to the word test."
});
We’ve now added a custom validation rule called “test”, maybe not so useful, but consider the next example. We add a rule to check whether a username is taken or not, with an imaginary AJAX request.
$.validation.addRule("xhr-test", {
    check: function(value) {
        $.get("/url-to-username-check", { username: value }, function(data) {
            if(data.isValid) {
                return true;
            }
            return false;
        });
    },
    msg : "Username already exists."
});
/*
Obviously, you’d want to improve the above 
example to handle possible AJAX failures.
*/
Some people will by now probably point out that the addRule method is essentially the same as making the object public and letting people add stuff to it themselves. Yes, that's true, but this a VERY simple abstraction. Should the code get any more advanced an abstraction like this could be helpful for anyone using your code.

Take a look inside

Lets take a look at our object in the firebug console.
console.log($.validation);
It should simply print out "object". If you click it you'll see the public methods we added earlier on. Let's see what the getRule method produces.
console.log($.validation.getRule("xhr-test"));
As you'll see, it returns the rule we added earlier. In OOP terminology we've now implemented getters and setters. Instead of allowing direct access to an objects private properties. It's better to have public methods that make these changes. It produces a cleaner API to the end user and it gives us more flexibility in case something else needs to run when modifying a property.

But someone told me the module pattern sucks...

Although I prefer this style of coding, it should be said that some developers neglect the idea of hiding properties and methods (a.k.a data encapsulation) in JavaScript. I think there are some very legitimate arguments linked to that statement. I leave it up to you to make up your own mind, nevertheless it's good to have knowledge of different design patterns even if you don't use them.

The form object

The form object will represent an instance of a form in the DOM.
var Form = function(form) {

    var fields = [];
    // Get all input elements in form
    $(form[0].elements).each(function() {
        var field = $(this);
        // We're only interested in fields with a validation attribute
        if(field.attr('validation') !== undefined) {
            fields.push(new Field(field));
        }
    });
    this.fields = fields;
}
A form has a number of fields belonging to it. We iterate over all the inputs and textareas that has a validation attribute using the jQuery each method. For each field there is, we create a new instance of the Field object which looks like this:
var Field = function(field) {
    this.field = field;
    this.valid = false;
}
We've defined some properties using the this keyword which refers to the object itself. We can now create any number of "form" instances with the new keyword.
var comment_form = new Form($("#comment_form"));
//another instance
var contact_form = new Form($("#contact_form"));
//Take a look inside the object
console.log(comment_form);
Providing your forms actually contain some fields with a validation attribute, you should see some interesting results when printing the object in the firebug console.

The JavaScript prototype object

This may seem like a tricky concept at first, but once you can wrap your head around prototypal inheritance, it's a really powerful and useful feature of the JavaScript language.

The problem

We have a large number of instances of the Field object, all of which we need to add some methods to. At first it may seem like a perfectly good idea to do the following:
Field.validate = function() {}
But this essentially means that if we have 30 fields instances, we will have 30 instances of the validate function, which is really a waste, since they all do the same thing.

The solution

Adding the validate method to the prototype object of Field will make all instances of Field inherit the validate method, but the validate method only exists in one place, so any changes to it will be reflected upon all instances of the Field object.
field.prototype.validate = function() {}
This feature should be used with care, especially when used on native javascript objects, before you fiddle around with it to much I recommend you read up further on the subject.

The Field validation methods

These are thetwo methods attached to the Field prototype object.
Field.prototype = {
    // Method used to attach different type of events to
    // the field object.
    attach : function(event) {

        var obj = this;
        if(event == "change") {
            obj.field.bind("change",function() {
                return obj.validate();
            });
        }
        if(event == "keyup") {
            obj.field.bind("keyup",function(e) {
                return obj.validate();
            });
        }
    },

    // Method that runs validation on a field
    validate : function() {

        // Create an internal reference to the Field object. 
        var obj = this, 
            // The actual input, textarea in the object
            field = obj.field, 
            errorClass = "errorlist", 
            errorlist = $(document.createElement("ul")).addClass(errorClass),
            // A field can have multiple values to the validation
            // attribute, seprated by spaces.
            types = field.attr("validation").split(" "), 
            container = field.parent(),
            errors = []; 

        // If there is an errorlist already present
        // remove it before performing additional validation
        field.next(".errorlist").remove();

        // Iterate over validation types
        for (var type in types) {

            // Get the rule from our Validation object.
            var rule = $.Validation.getRule(types[type]);
            if(!rule.check(field.val())) {

                container.addClass("error");
                errors.push(rule.msg);
            }
        }
        // If there is one ore more errors
        if(errors.length) {

            // Remove existing event handler
            obj.field.unbind("keyup")
            // Attach the keyup event to the field because now
            // we want to let the user know as soon as she has
            // corrected the error
            obj.attach("keyup");

            // Empty existing errors, if any.
            field.after(errorlist.empty());
            for(error in errors) {

                errorlist.append("<li>"+ errors[error] +"</li>");        
            }
            obj.valid = false;
        } 
        // No errors
        else {
            errorlist.remove();
            container.removeClass("error");
            obj.valid = true;
        }
    }
}
As a last step, we're going to edit the Field object we defined earlier:
var Field = function(field) {

    this.field = field;
    this.valid = false;
    this.attach("change"); // add this line.
}
Now each field will validate upon the "change" event.

Finishing the Form Object

Now our Field object is pretty much complete, let's add a few more features to the Form object before moving on to the actual jQuery plugin implementation.
Form.prototype = {
    validate : function() {

        for(field in this.fields) {

            this.fields[field].validate();
        }
    },
    isValid : function() {

        for(field in this.fields) {

            if(!this.fields[field].valid) {

                // Focus the first field that contains
                // an error to let user fix it. 
                this.fields[field].field.focus();

                // As soon as one field is invalid
                // we can return false right away.
                return false;
            }
        }
        return true;
    }
}

The jQuery plugin methods

We're going to use the jQuery extend method to make our plugin accessible as methods on any jQuery object.
$.extend($.fn, {

    validation : function() {

        var validator = new Form($(this));
        $.data($(this)[0], 'validator', validator);

        $(this).bind("submit", function(e) {

            validator.validate();
            if(!validator.isValid()) {

                e.preventDefault();
            }
        });
    },
    validate : function() {

        var validator = $.data($(this)[0], 'validator');
        validator.validate();
        return validator.isValid();
    }
});
The validation method is what we use to create a new validation instance associated to a form. You can see that we're creating a new form instance and also binding the a submit event handler to run the validation upon form submission.

The jQuery $.data method

This is pretty nifty feature and allows us to store data assoicated to a jQuery object. In this case, we are storing an instance of the form object inside the object passed into the plugin. In the validate method, that we use to validate the form at anytime, we can now call the already existing form instance, instead of creating a new one.

Usage

Based on the plugin that we've now built, here's some usage examples.
$(function(){ // jQuery DOM ready function.

    var myForm = $("#my_form");

    myForm.validation();

    // We can check if the form is valid on
    // demand, using our validate function.
    $("#test").click(function() {

        if(!myForm.validate()) {

            alert("oh noes.. error!");
        }
    });
});
 
You can look at the full jquery.validation.js code itself, feel free to use it.

That's all

I hope you found this article useful and educational, the example plugin is far from the perfect form validation script but that was not the primary goal of this article, but rather write nicely structured JavaScript code in an object oriented approach.