Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

November 2011 - Posts

Performing Validation using the JQuery Validation library/plugin

This another post that is focusing on how to use JQuery in ASP.Net applications. If you want to have a look at the other posts related to JQuery in my blog click here

In this post I would like to show you how to perform client-side validations using the JQuery validation plugin.

Some basic level of knowledge of JQuery is assumed.

Sadly, we canot cover the basics of JQuery in this post so here are a few resources for you to focus on

 You can download the Jquery Validation plugin from here.We will use only the jquery.validate.js file from the downloaded files.

If you want to have a look at some other posts of mine regarding validation using the ASP.Net validation controls have a look in this and also this post.

1) Launch Visual Studio 2010. I have Visual Studio 2010 ultimate edition but Express edition will also work. Create an ASP.Net Web site.Give your site an appropriate name.

2) We want to download and use the latest version of JQuery. We need to download it first. Then we need to remove the version that ships with VS 2010, 1.4.1.We will place inside the Scripts folder the 1.7 version of the JQuery library.

3)  Add a new item to your site, a web form. Name it, Validation.aspx. This is the markup inside the body tag:

 

<form id="frmMain" runat="server">
 <fieldset>
   <legend>Please provide your information</legend>
    <p>
<label for="txtName">Name</label>
<input id="txtName" name="txtName" type="text" class="input" />
</p>
	<p>
<label for="txtUsername">Username</label>
<input id="txtUsername" name="txtUsername" />
	</p>
	<p>
	<label for="pwdPassword">Password</label>
<input id="pwdPassword" name="pwdPassword" type="password" />
	</p>
	<p>
	<label for="pwdConfirmPassword">Confirm password</label>
<input id="pwdConfirmPassword" name="pwdConfirmPassword" type="password" />
		</p>
		<p>
	<label for="txtEmail">Email</label>
	<input id="txtEmail" name="txtEmaill" class="input" />
		</p>
		<p>
	<label for="txtURL">URL</label>
	<input id="txtURL" name="txtURL" class="input" />
		</p>
 
        <p>
         <label for="dotnetlanguage">Preferred .Net Language</label>
        <input id="csharp" name="dotnetlanguage" type="radio" value="0" />
                <label id="csharp_l" for="csharp_c">C#</label>
	<input id="vbnet" name="dotnetlanguage" type="radio" value="1"  />
 <label id="vb_l" for="vb.net">VB</label>
        
        </p>
		<p>
	<label id="lblComment" for="txtComment">Comments</label>
	<textarea id="txtComment" name="txtComment" rows="5" cols="55"></textarea>
		</p>
 
        <p>
        <label for="VSversion">Visual Studio Version you are using</label><br/>
  <input name="vsversion[]" id="1" value="1" type="checkbox" /> <label for="1">
VS 2010</label><br/>
  <input name="vsversion[]" id="2" value="2" type="checkbox" /> <label for="2">
VS 2008</label><br/>
  <input name="vsversion[]" id="3" value="3" type="checkbox" /> <label for="3">
VS 2005</label><br/>
        
        </p>
		<p>
<label for="chkAgree">Please agree to Terms and Conditions: </label>
<input type="checkbox" class="checkbox" id="chkAgree" name="chkAgree" />
		</p>
		<p>
	<input type="submit" value="Submit"/>
		</p>
	</fieldset>
	</form>

 

5) Let me explain what the form looks like. This is a typical form. It has fields like Name which is a required field.It has also a UserName field that is required and has at least 8 characters.Then we have two password fields. The password field and the confirm password field must be at least 6 characters and match.An Email field is also required and must be valid.A URL field is not required but if the user chooses to fill in the URL field that must be a valid URL. We have radio button fields , that the user must at least select one option. Then we have 3 checkbox fields and the user must choose at least one. Finally there is a checkbox field that must be checked (terms and conditions)

As you can see these are all items of a typical form.

We will check for those conditions using JQuery.

6) In the head section of the .aspx page add a reference to the following .js files

<script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.js" type="text/javascript"></script>

 

7) Also in the head section I will include some styles.We will use these styles to style various elements of the form and what the visual indication would be once the validation fails.In this case it would be a red border indicating the failed validation.

<style type="text/css">
		#frmMain {
			width600px;
		}
		#frmMain label {
			displayinline-block;
			width150px;
			vertical-aligntop;
			font-weightbold;
		}
		.input {
			width400px;
		}
		#frmMain label.error {
			margin-left155px;
			colorRed;
			font-weightnormal;
			width400px;
		}
		#frmMain input.error {
			border1px solid Red;
		}
	</style>

 

8) Now I will add again in the head section the javascript code that makes the validation possible.

	<script type="text/javascript">
	    $.validator.setDefaults({
submitHandler: function () { alert("We got your form data"); }
	    });
 
	    $(function () {
	        $('#frmMain').validate({
	            rules: {
	 txtName: "required",
	 txtUsername: { required: true, minlength: 8 },
	 pwdPassword: { required: true, minlength: 6 },
pwdConfirmPassword: { required: true, minlength: 6, equalTo: '#pwdPassword' },
	 txtEmail: { required: true, email: true },
	 txtURL: { url: true },
	 chkAgree: { required: true },
	 dotnetlanguage: { required: true },
	 'vsversion[]': { required: true, minlength: 1 }
	            },
 
	            messages: {
	   txtName: "Please enter your first and last names.",
	   txtUsername: { required: 'Please enter a username.',
	   minlength: 'The username must be at least eight characters long.'
	                },
	   pwdPassword: {
	   required: 'You must enter a password.',
	   minlength: 'The password must be at least 6 characters long.'
	                },
	   pwdConfirmPassword: {
	   required: 'You must enter a confirmation password.',
	   minlength: 'The password must be at least 6 characters long.',
	   equalTo: 'The two passwords you enter must match.'
	                },
	   txtEmail: 'Please enter a valid email address.',
	   dotnetlanguage: 'Choose your favourite .Net Language',
           'vsversion[]''Select at least one option',
	   chkAgree: 'You must agree to the usage policy.'
          
	            }
	        });
 
	        $('#txtUsername').focus(function () {
	            var name = $('#txtName').val();
	            name = name.replace(' ''');
	            name = name.toLowerCase();
	            if (name && !this.value)
	                this.value = name;
	        });
	    });
	</script>

9) Let me explain what I am doing with the JQuery above

 $.validator.setDefaults({
submitHandler: function () { alert("We got your form data"); }
	    });

In this bit of code we have a custom function that runs an alert box when the data is successfully posted.

Then I use the JQuery ready function to set up validation rules and messages

<snippet>

 

 $(function () {
	        $('#frmMain').validate({
	            rules: {
                        txtName: "required",
	                txtUsername: { required: true, minlength: 8 }, 

 

 ......

 

 messages: {
	     txtName: "Please enter your first and last names.",
	  txtUsername: { required: 'Please enter a username.',
minlength: 'The username must be at least eight characters long.'
	                },

 

</snippet>

 

Rules and messages are passed as arguments to the validate method.

With the rules you can set up very easily the various validation criteria the validation process must conform to.You can see how we set up the required fields and the minimum length for a field. You can also see how we check for valid emails and urls.You can also see how we set up the validation for passwords that must match and various radio (one must be selected) and checkbox controls(one must be selected from the first set of checkboxes and then the final checkbox must be checked).Have a look below. There is nothing difficult really.

    $('#frmMain').validate({
	            rules: {
	                txtName: "required",
	                txtUsername: { required: true, minlength: 8 },
	                pwdPassword: { required: true, minlength: 6 },
pwdConfirmPassword: { required: true, minlength: 6, equalTo: '#pwdPassword' },
	                txtEmail: { required: true, email: true },
	                txtURL: { url: true },
	                chkAgree: { required: true },
	                dotnetlanguage: { required: true },
	                'vsversion[]': { required: true, minlength: 1 }
	            },

 

Have a look at the jquery.validate.js to see how these methods are implemented. Have a look at the minlength validation method in the jquery.validate.js method.

minlength: function(value, element, param) {
	return this.optional(element) || 
this.getLength($.trim(value), element) >= param;
		},

 

 

In the messages section we can set up the various text messages printed on the screen whenever the validation fails.

 messages: {
    txtName: "Please enter your first and last names.",
    txtUsername: { required: 'Please enter a username.',
    minlength: 'The username must be at least eight characters long.'
	},
     pwdPassword: {
   required: 'You must enter a password.',
   minlength: 'The password must be at least 6 characters long.'
	   },
   pwdConfirmPassword: {
  required: 'You must enter a confirmation password.',
 minlength: 'The password must be at least 6 characters long.',
 equalTo: 'The two passwords you enter must match.'
	   },
   txtEmail: 'Please enter a valid email address.',
  dotnetlanguage: 'Choose your favourite .Net Language',
  'vsversion[]''Select at least one option',
  chkAgree: 'You must agree to the terms and conditions.'
          
}
 });
 
  $('#txtUsername').focus(function () {
	     var name = $('#txtName').val();
	     name = name.replace(' ''');
	     name = name.toLowerCase();
	      if (name && !this.value)
	      this.value = name;
	        });

 

Finally when the username field gets the focus I am "suggesting"  a username by concatenating the first and last name of the first field. I also strip out all spaces and make them lowercase.

There is nothing difficult here.That is the magic of JQuery. Once you get your head around JQuery you can see how simple it is to use it.You can write very little code but it is so powerful.

10) Run your application and play around with the various validation fields. Make sure you fail the validation and see how JQuery picks up all the errors. Finally submit the form with no errors.

That is all folks.

Email me if you need the source code.

Hope it helps!!!

Creating a simple watermark effect using JQuery

This another post that is focusing on how to use JQuery in ASP.Net applications. If you want to have a look at the other posts related to JQuery in my blog click here

In this post I would like to show you how to create a simple watermark effect using JQuery.Watermark is a great way to provide users with informarion without using more space on the screen.

Some basic level of knowledge of JQuery is assumed.

Sadly, we canot cover the basics of JQuery in this post so here are a few resources for you to focus on

 

1) Launch Visual Studio 2010. I have Visual studio 2010 ultimate edition but Express edition will also work. Create an ASP.Net Web application.Choose C# as the development language.Give your application an appropriate name.

2) We want to download and use the latest version of JQuery. We need to download it first. Then we need to remove the version that ships with VS 2010, 1.4.1.We will place inside the Scripts folder the 1.7 version of the JQuery library.

3)  Add a new item to your application, a web form. Name it, Watermark.aspx. Do not include the master page. This is the markup.We have two textboxes.Notice the watermark css class.


<body>
   <form id="form1" runat="server">
    <div class="mainDiv">
         
   <asp:TextBox ID="fname" class="watermark" Text="Type your First Name" 
    Tooltip="Type your First Name" runat="server"></asp:TextBox><br />
    <asp:TextBox ID="lname" class="watermark" Text="Type your Last Name" 
     Tooltip="Type your Last Name" runat="server"></asp:TextBox>
     <br /><br />
        <asp:Button ID="submit" runat="server" Text="Click me!!!" />
     
    </div>
  
    </form>
</body>
 


4) We will create the necessary styles.Add a new item to your application. Name it watermark.css and place it in the Styles folder.

body
{
background-color:#eaeaea;
}
 
 
.mainDiv
{
    background-color:Navy;
 
    width:410px; 
    padding:10px;
 
}
 
.watermark
{
  font-familyArial;
     font-size:0.7em;
     font-weight:bold;
     color:#808080;
}


5) Obviously at some point we need to reference the JQuery library and the external stylesheet. In the head section Ι add the following lines.

   <link href="Styles/watermark.css" rel="stylesheet" type="text/css" />
 
    <script src="Scripts/jquery-1.7.js" type="text/javascript"></script>

 

6) Inside the head section we also write the simple JQuery code.

    <script type="text/javascript">
        $(function () {
 
            $(".watermark").each(function () {
                $txt = $(this);
                if ($txt.val() != this.title) {
                    $txt.removeClass("watermark");
 
                }
            });
 
            $(".watermark").focus(function () {
                $txt = $(this);
                if ($txt.val() == this.title) {
                    $txt.val("");
                    $txt.removeClass("watermark");
                }
            });
 
            $(".watermark").blur(function () {
                $txt = $(this);
                if ($.trim($txt.val()) == "") {
                    $txt.val(this.title);
                    $txt.addClass("watermark");
                }
            });
        });        
 
    </script>

Let me explain what the code does.In all cases with JQuery we start by checking that the DOM is loaded. We do that by using the ready function.

When the page loads both the textboxes display a message to the user. Note that the tooltip tag is rendered to title when the page is loads.

When the textbox gains focus (focus function) we remove the watermark by using the removeClass function.As you can see we compare the textbox value with the title property ( tooltip )

$(".watermark").focus(function () {
                $txt = $(this);
                if ($txt.val() == this.title) {
                    $txt.val("");
                    $txt.removeClass("watermark");
                }
            });

When moving the focus to a different control without entering a value, we put the watermark back by using the addClass function.

 $(".watermark").blur(function () {
                $txt = $(this);
                if ($.trim($txt.val()) == "") {
                    $txt.val(this.title);
                    $txt.addClass("watermark");
                }
            });

 

When the user fills in both fields we do not need to have any watermark anymore and we remove it from both textboxes. We compare the values of the textbox and the title and if they are different we remove the watermark by using the removeClass function

            $(".watermark").each(function () {
                $txt = $(this);
                if ($txt.val() != this.title) {
                    $txt.removeClass("watermark");
 
                }
            });

 

I hope you appreciate the fact that we can do so much with a few lines of JQuery code.This is the big power of JQuery library. We can do more with less. That means we have less code to write, we are more productive and our code is easier to read and more maintainable. 

View the web page on the browser and see for yourself the results.Email me if you need the source code or leave a comment with your email.

Hope it helps!!

Creating a simple accordion with JQuery

This another post that is focusing on how to use JQuery in ASP.Net applications. If you want to have a look at the other posts related to JQuery in my blog click here

We all know that there is always a limited space in our web page to show content.In this example I would like to show you how to create an accordion "effect" on a simple .aspx page.

Some basic level of knowledge of JQuery is assumed.

Sadly, we canot cover the basics of JQuery in this post so here are a few resources for you to focus on

 

1) Launch Visual Studio 2010. I have Visual studio 2010 ultimate edition but Express edition will also work. Create an ASP.Net Web application.Choose C# as the development language.Give your application an appropriate name.

2) We want to download and use the latest version of JQuery. We need to download it first. Then we need to remove the version that ships with VS 2010, 1.4.1.We will place inside the Scripts folder the 1.7 version of the JQuery library.

3)  Add a new item to your application, a web form. Name it, Accordion.aspx. Do not include the master page. First we need to add some content to the page.In this example I will create a FAQ page. Each question will be a part of the accordion.This is the markup.

<body>
    <form id="form1" runat="server">
    <div>
    <div class="FAQ">
	<h2>How do I select an item using class?</h2>
	<p>This code selects an element with a class of "myCssClass". Since any number of elements can
 have the same class, this expression will select any number of elements.
 
<span>$('.myCssClass')</span></p>
	<h2>How do I select an item using an ID?</h2>
	<p>This code selects an element with an ID of "myDivId". Since IDs are unique, this 
expression always selects either zero or one elements depending upon whether or not an element 
with the specified ID exists.
 
 <span>$('#myDivId')</span></p>
	<h2>How do I determine the state of a toggled element?</h2>
	<p>You can determine whether an element is collapsed or not by 
using the :visible and :hidden selectors.<br />
 
 <span>var isVisible = $('#myDiv').is(':visible');</span><br />
 <span>var isHidden = $('#myDiv').is(':hidden');</span></p>
	
</div>
    </div>
    </form>
</body>
 

4) We will create the necessary styles.Add a new item to your application. Name it Accordion.css and place it in the Styles folder.

body {
	margin10px auto;
	width670px;
}

.FAQ {
	width580px;
	border-bottomsolid 1px #c4c4c4;
}
.FAQ h2 {
	background#eb7515;
	padding10px 10px;
	margin0;
	font-family:Verdana;
	font-size:1.2em;
	color:#fff;
	bordersolid 1px #C50F0F;
	border-bottomnone;
	cursorpointer;
}
.FAQ h2:hover {
	background-color#262B2A;
}

.FAQ p {
	background#ADA6A6;
	margin0;
	padding10px 15px 20px;
	border-leftsolid 1px #c4c4c4;
	border-rightsolid 1px #c4c4c4;
	displaynone;
}

.FAQ span 
{
    color:Olive;
    background-color:#DCDCDC;
    font-family:Arial;
    font-size:1.1em;
    
}

We use the css rules to style the various elements of the markup.

5) Obviously at some point we need to reference the JQuery library and the external stylesheet. In the head section Ι add the following lines.

   <link href="Styles/accordion.css" rel="stylesheet" type="text/css" />
 
    <script src="Scripts/jquery-1.7.js" type="text/javascript"></script>

 

6) Inside the head section we also write the simple JQuery code.

<script type="text/javascript">
    $(document).ready(function () {
 
        $(".FAQ p").eq(0).show();
 
        $(".FAQ h2").click(function () {
            $(this).next("p").slideToggle("slow");
		
     
          
        });
 
    });
</script>

Let me explain what the code does.In all cases with JQuery we start by checking that the DOM is loaded. We do that by using the ready function.

Then by using the eq selector I show the contents of the first paragraph that is inside the div with the class FAQ.In order to show the contents I use the show function.

When the element with class ".FAQ h2"  is clicked (We grab that object by using - $(".FAQ h2") -) it will slide the contents of the first paragraph (p) up or down depending on their current status/position .I am using the slideToggle function to achieve that. This function displays or hide the matched elements with a sliding motion.Have a look at the function's full explanation here.

I hope you appreciate the fact that we can do so much with a few lines of JQuery code.This is the big power of JQuery library. We can do more with less. That means we have less code to write, we are more productive and our code is easier to read and more maintainable. 

View the web page on the browser and see for yourself the results.Email me if you need the source code or leave a comment with your email.

Hope it helps!!

Creating a simple slider panel with JQuery

This another post that is focusing on how to use JQuery in ASP.Net applications. If you want to have a look at the other posts related to JQuery in my blog click here

We all know that there is always a limited space in our web page to show content.In this example I would like to show you how to create a slider panel that the users of your site can slide down so they can see the content.

Some basic level of knowledge of JQuery is assumed.

Sadly, we canot cover the basics of JQuery in this post so here are a few resources for you to focus on

 

1) Launch Visual Studio 2010. I have Visual studio 2010 ultimate edition but Express edition will also work. Create an ASP.Net Web application.Choose C# as the development language.Give your application an appropriate name.

2) We want to download and use the latest version of JQuery. We need to download it first. Then we need to remove the version that ships with VS 2010, 1.4.1.We will place inside the Scripts folder the 1.7 version of the JQuery library.

3)  Add a new item to your application, a web form. Name it, SilderPanel.aspx. Do not include the master page. First we need to add some content to the page.

<body>
    <form id="form1" runat="server">
  
<div id="mainpanel">
<p><span>JQuery</span> is a fast and concise JavaScript Library that simplifies
 HTML document traversing, event handling, animating, 
and Ajax interactions for rapid web development. 
jQuery is designed to change the way that you write JavaScript.</p>
</div>

<p class="slider"><a href="#">Click here to slide!!!</a></p>
   
    </form>
</body>

 

We want the markup inside the div mainpanel, to be placed on the top of the page and in the center. When someone clicks on a button that is on the bottom of that slider panel, the panel will slide down slowly and when it clicks it again to slide up in a rather slow way.

4) Add a new folder to your application. Name it images.We will have an image placed in that folder. You can download it from this link.The name of the image is panel.gif

5) Add a new item to your application. Name it Slider.css

This is the code in the .css file

body {
	margin0 auto;
	padding0;
	width650px;
	font-familyVerdana;
}

#mainpanel {
	background#B5B6BC;
	height300px;
	displaynone;
}
.slider {
	margin0;
	padding0;
	border-topsolid 7px #0B4213;
	backgroundurl(images/panel.gif) no-repeat center top;
}
.slider a {
	
	text-aligncenter;
	width184px;
	height31px;
	padding10px 10px 10px 10px;
	margin0 auto;
	displayblock;
	font-family:Tahoma;
	font-size:1.2em;
	color#000;
	text-decorationnone;
}


span
{
    color:Navy;
    text-decoration:none;
    font-size:1.4em;
    font-style:italic;
}

We use the css rules to style the various elements of the markup.

6) Obviously at some point we need to reference the JQuery library and the external stylesheet. In the head section Ι add the following lines.

    <script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
 
    <link href="Slider.css" rel="stylesheet" type="text/css" />

 7) Inside the head section we also write the simple JQuery code.

<script type="text/javascript">
    $(document).ready(function () {
 
        $(".slider a").click(function () {
            $("#mainpanel").slideToggle("slow");
            
        });
 
 
    });
</script>

 

Let me explain what the code does.When the element with class ".slider a"  is clicked it will slide the contents of the element with id "mainpanel" down and when clicked again it will slide the contents up again. It is that simple.I am using the slideToggle function to achieve that. Have a look at the function's full explanation here.

I hope you appreciate the fact that we can do so much with a few lines of JQuery code.This is the big power of JQuery library. We can do more with less. That means we have less code to write, we are more productive and our code is easier to read and more maintainable.

View the web page on the browser and see for yourself the results.Email me if you need the source code.

Hope it helps!!!

Posted: Nov 23 2011, 11:48 PM by nikolaosk | with 1 comment(s) |
Filed under: , ,
More Posts