Share the ideas and thoughts, become united ...

Thursday, October 28, 2010

How CSS Box Model Works - Beginner

Well it has been may days since I wrote my last blog. I was busy with my work and it was very messy. It has crossed my mind several times to write a blog, but I couldn't find any luxury time to write one.

So, I have came up with a small topic regarding the CSS Box Model.

CSS box model is a model where you treat your every component as a box. Then you using these box (i,e your html element) and put it around the page to setup the layout. Well most of the beginner coder knows how the CSS box model works.

But still I think it might be good idea for those who didn't to know how the CSS box model actually works. So, that they can actually begin to understand the CSS positioning and styling by themselves.

Now let us see the box model


As you can see the HTML element is surrounded by Padding.
Padding is the space around the HTML element. In CSS tag you can use the Padding property as below
  • padding:value;  [this will put free space equal to the value (say 3px) around the HTML element.]
  • padding:val1 val2; [this syntax will set free space equal to val1 in up-down direction and val2 in left-right direction]
  • padding-left:value; [to explicitly define the left padding value for the html element]
  • padding-right:value; [to explicitly define the right padding value for the html element]
  • padding-top:value; [to explicitly define the top padding value for the html element]
  • padding-bottom:value; [to explicitly define the bottom padding value for the html element]

The Margin property is also like the padding property but unlike the padding free space, which cannot be filled with other elements, margin space can contain other elements.
You can think padding and the HTML element as a HTML element itself. But that is not necessarily true for the margin property.
Margin property will put up margin equal to the value you set in the margin property.
You can use many form of margin property and they all like padding property usage.
  • margin:value;  [this will put margin space equal to the value (say 3px) around the HTML element.]
  • margin:val1 val2; [this syntax will set margin space equal to val1 in up-down direction and val2 in left-right direction]
  • margin-left:value; [to explicitly define the left margin value for the html element]
  • margin-right:value; [to explicitly define the right margin value for the html element]
  • margin-top:value; [to explicitly define the top margin value for the html element]
  • margin-bottom:value; [to explicitly define the bottom margin value for the html element]

Now the offset is used to put the element into the right position and usually have four properties-
  • left:value;
  • right:value;
  • bottom:value;
  • top:value;
All of them takes a single value or percentage of the total width of the document on the screen (generally screen resolution).  They tells the browser about the elements to be placed according to the given offset value.

Very basic stuff discussed here, but I think if any one has clear idea how the model works they can understand how to place the element rightly.

One last point, different browser handles the box model differently. The model here I describe works best with firefox browser. There is only one big difference with the IE's box model is that, in IE's box model the padding isn't included in to the element itself. But in firefox (gecko to be more exact) box model consider padding as associated with the html element itself.

Thank you for reading the post. If you have any question, suggestion or anything, please leave a comment. Keep in touch.

Friday, August 13, 2010

PHP SQL Injection Prevention

The old school SQL Injection probably does not work in today's modern websites. But those who are new to PHP website development find themselves wondering around the web to learn to eliminate the SQL injection.

There is a very simple function in PHP to stop SQL injection. Consider We have a table :-
Table fake_customers
===============
id        name
--       ------
1          X
2          Y
3          Z

If we pass the ID by the get method the following code is prone to SQL injection -
$q = "select * from fake_customers where id = $id";
now what if we pass "1 and id>1" in the id parameter? Then the query will be like
$q = "select * from fake_customers where id = $id"; // select * from fake_customers where id = 1 and id>1 -- SQL injected !!!

A better approach is to use the mysql_real_escape_string() to escape the SQL escape characters.
here is the solution -
$q = sprintf("select * from fake_customers where id = %d", mysql_real_escape_string($id));

Pretty easy, isn't it?

For any suggestion or question, please leave a comment.

Monday, August 9, 2010

PHP Date Tips & Usage

We all need the current date now and then. Today I will review some of the usage of PHP date functions.

$array = getdate();
  • There are many ways to get the current date. Probably the easiest one is getdate() function.
  • The return type of the getdate() is an array. So the values of the current time is mapped into a (key => value) pair. i,e for every value there will be a mapped key.
  • Useful Keys are
    • minutes  - returns minutes
    • seconds  - returns seconds
    • hours    - returns hours
    • mday     - returns day of the month (no of the day of current month) (between 1-31)
    • yday     - returns day of the year (between 1-365)
    • month    - textual representation of the current month
    • mon      - returns the current month number (between 1-12)
    • year     - returns the current year
  • e,g -
$today = getdate();
echo $today['mon'] . '/' . $today['mday'] . '/' . $today['year'];     // outputs --> mm/dd/yyyy
Another way of getting the date is the date function itself.


$string = date($format);
  • The format is a string which defines the format of the date
  • The useful formats are -
    • d   - the day of the month (between 1-31)
    • D  - short textual representation of the day of the month (e,g Sun, Mon etc.)
    • t    -  no of days in that month (e,g 28 for feb, 31 for jan etc.)
    • m  - the month of the year (between 1-12)
    • M - short textual representation of the month of the year (e,g Jan, Feb etc.)
    • y  - two digit representation of the year (e,g 99)
    • Y - four digit representation of the year (e,g 2099)
    • L - 1 if this year is a leap year, 0 otherwise
    • h  - hours (in 12 hrs format)
    • H - hours (in 24 hrs format)
    • i - minutes
    • s - seconds
  • e,g -
echo date("D, d-M, Y : H:i:s");   // we are telling the php parser that we will use short textual day name first then the actual day number of that month. Then we will show the short name of the month with a dash in between the day and the month. Lastly we will show the year in full 4 digit format. the last part shows the time. We used the H for showing the time in 24 hrs format i and s for minutes and seconds. We have to add 'a' or 'A' to get the AM/PM display in the format.
 If you have any suggestion or question, please feel free to drop a comment.

Tuesday, July 6, 2010

Bringing Life to your fedora

I am a newbie user of linux, particularly fedora. I liked fedora when I first used it. From my linux experience I know that sometimes it can be pretty frustrating. So I am here to share my experience with you guys.

Today I am going to discuss some important tools necessary to bring life to your fedora box.

[ RPM FUSION REPOSITORY - A Must

1. RPM Fusion Repository: We are going to install a lot of software through YUM, which downloads and installs software into your system. The fedora system comes with default repositories. But we need the RPM fusion repository. Follow the lead -
  • Go to RPM FUSION and select the RPM Fusion Free (because we will be installing only free softwares :) ) or
  • You can do the following -
su -c 'rpm -Uvh http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-stable.noarch.rpm http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-stable.noarch.rpm'
Now you have a "really needed weapon" in your arsenal. RPM fusion has a database of free software which are not included in the fedora repository (default repository). You can install free codes from the RPM fusion database. Now you can install the codes and listen to your favorite mp3 file. :) -- Really the Life Saver!




[ GStreamer - Ultimate OpenSource Multimedia FrameWork] 


We all need to listen to musics or watch movies. But alas!!! in fedora they removed all the decoders which has licensing issue (most of them do). So, fedora left you with some opensource solution i guess (ogg vorbis). Don't worry. fedora uses GStreamer Framework for multimedia purpose. So, you are just one command away from listening to mp3 or watching mkv video or even dvd files :).

Just open your terminal and type these magic words -
yum install gstreamer-plugins-good-0.10.16-7.fc12.i686
After installation just try to open a mp3 file with your rhythm box and listen to your favourite multimedia. Enjoy the Life!

[ Download Manager Solution (FlashGot + Prozilla) ]

Fedora comes with one of the best browser "Firefox". Your tension of which browser to use is gone. But what about the download manager? Well Firefox's built in browser is not good enough. Don't worry - "where there is a problem there's a way also". You can use the ultimate combo of FlashGot and Prozilla or any other good DM. FlashGot is a firefox plugin which enables one to redirect download URL from firefox to another 3rd party download manager.

1. Install the FlashGot Plugin
2. Install the Prozilla DM using Yum
yum install proz
This command will automatically download and install the prozilla into your system.
3. Configure the FlashGot to transfer the download URL to Prozilla
Ahhh. All done. Enjoy the net ...

I am going to add more and more tools to the fedora. For the time being, Keep in touch.

Saturday, July 3, 2010

Wordpress Theme Customization Video Tutorial

Many of my friends were asking about Wordpress theme customization. Well I have used WP before, but I never customized theme for it. So, I wonder around the net to find a good WP tutorial site, which can be used to quickly learn the theme customization of the WP.

Today I am going to share two site with you which contains good WP learning material for theme customization.

For those who are eager to learn it very quickly they have to use the video tutorial site. And I found
CSS TRICKS
very helpful for it.

For those who have a low speed internet connection or prefer text based tutorial they can check
THEME SHAPER site. It has step by step tutorial of how to customize a theme for WP.

Hopefully this links will come to your aids.

Wednesday, April 28, 2010

jQuery: Nice looking slide show in no time !!

Sometimes we need to add sideshows to our website. Today we are going to see how to achieve it very quickly with a little bit of coding. We will use the jQuery to reduce the amount of coding we have to do. Now let us see how can we do it -

What we will need -
  1. jQuery script [jquery-1.3.2.min.js]
  2. Images which will appear in the slide show
  3. Some JS and HTML coding
 First we will need to add the jQuery library file.
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
 Next we need to setup our own jQuery code to define the slide show materials and properties.

 <script type="text/javascript">
    var srrc = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"];
srrc is the array variable which holds the image paths of the slide show images. You can add as many path as you want. 
    var id =0;
    var max = 5;
id is the variable whose value tells the browser to load which images from the srrc array. It is acting as a index variable for the srrc array. max variable defines the maximum number of images defined in the image array.
function run() {
        id = id + 1;
        id = id % max;
        var cur = srrc[id];
 Nothing much to describe here. cur variable holds the path for current image which we are going to display.
        $("#images").hide();
        $("#images").attr({src: cur, alt:'', border:0});
        $("#images").fadeIn("slow");
$("#images") will return the handle of the html element with the id of images. Don't worry about the element for now, it is a <img> element, we will be introduced with it in the latter section.
First we used the jQuery hide() function to hide the element.
Then we use the jQuery attr() function to add the html attribute to the <img> element. The important part is the src: cur. cur variable is holding the image path for current image. So, we just add the image path to the img tag. It can be translated as <img src="the image path in the cur variable">.
Now the img element has the image but it is hidden. Now we show the whole element using the jQuery fadeIn() effect. This adds nice looking transition effect while changing the images.
        setTimeout(run,10000);
    }
 Now to run this script indefinitely we use setTimeout() javascript function. We want to keep each images for 10 secs. So the second parameter is 10000 (it is in mili secs). The first parameter is a callback function.
Whenever 10 secs has passed since the timeOut() function is called, the callback function is called automatically.
    $(document).ready(setTimeout(run,3000));
</script>
 Lastly we use the $(document).ready() function to initiate the first call to the run function.

Now all we need is to add the <img> element into body section of the html page
<img src="1.jpg" width="395px" height="245px" alt="" id="images" border="0" />
 We are all done.
Here is the total work.
If you have any suggestion or question please leave a comment.

Friday, April 23, 2010

Activate GPRS on China Mobile's Cell Phone in Win7

This is a complete step by step guide to use your China Mobile as a GPRS modem for connecting to the internet.

1. Plug-in your mobile into USB and select the "COM Port" if any option on your mobile device pops up.

2. Right click the "Computer" on desktop and go to "properties". Click the "Device Manager" on the top left side of the properties window.

3. Find out your modem device. It should be appear with a yellow exclamation sign.

mtk
4. Download this driver. [MTK CPU USB Driver] 17 KB

5. Double click the sign in the device manager to bring up the properties window of the modem device. Click "Update driver" located in the lower left side of the dialog. Now Select the "Browse my computer for driver software" and show the location of the driver. Click Next to install the driver. Select "continue or install anyway" if any dialog pops up saying that the driver is not signed digitally.


6. Now the driver for your modem should be installed. It should say something like "62xx USB Modem Driver (COM yy)".


7. Now open up the start menu and in the search box type "modem". Now select the "Phone & Modem" located under the "Control Panel" section. You can also go to the control panel and in the search box (upper right corner) type "modem" and then choose the "Phone & Modem".

8. After opening the "Phone and Modem" palette, select the "Modems" tab. Click "Add" to add new modem. Now a "Add hardware wizard" will pop up. Check "Don't detect my modem" and click next.


9. Now download this modem driver. [MT6225_Modem_Driver] 31KB

9. On the next section click the "Have disk" button and browse for the modem driver. You will see the modem driver, but the driver is not digitally signed. Click next to continue installation with the modem driver.


10. Now in the next section select the "COM yy" as the communication port for your modem. Click next to add the modem. You can find your modem's "COM yy" from the device manager.


11. Your Modem is now installed. You can create dial-up connection using it. Now let us test the modem.
Again open the "Phone & Modem" control panel palette. Go to "Modems" tab and double click the installed modem. Modem's property dialog will pop up. Now go to "Diagnostics" tab and click "Query Modem". After a short while it will show the result of the query. This is a proof which indicates that your modem is working.



Now create a dial-up connection using this modem and enjoy edge or gprs service.
This walk-through is for win7 but you can use it for win xp also.
If any of the link becomes invalid, please notify me. or you can google out the driver yourself.

For any question and suggestion, please leave a comment.

Saturday, April 17, 2010

GIMP: Create Nice Looking Button For Your Website

It is very easy to create nice looking button in modern graphics editor like PS CS3. I will show the basic behind creating in creating such nice and cool looking button. I am using GIMP (GNU Image Manipulation Program) for creating such an image. The method is almost similar in PS CS3 or earlier.

Here is the button which we are gonna create using the graphics editor -



1) First we need to create an empty space for creating the button. I am using 300x150 pixel dimension stage. The stage is set to full transparent. This is how it looks like -


2) Create a new layer to create the background effect of the button. Use (CTRL+L) to bring out the layer dialog if it is not showing.


3) Now select the "Rectangle Select Tool" from the toolbox and draw a rectangle. See the option for the "Rectangle Select Tool" and find and activate the "Rounded Corner" property. This will make the selection look like a rounded box.


4) Now Select the "Bucket Fill Tool" from the toolbox. Select your desired background color and click the selection to fill the selection with that color. This is our background of the button.


5) Now we have to create the top layer of the button. Again we create a layer and then draw a similar rectangle tool, but this time it is a little smaller than the background.


6) After creating a slight smaller selection similar to the background on top of the background, we have to fill the selection again to get the shape of the selection. But this time we will not use the "Fill Bucket Tool"; instead we will use the "Gradient Fill Tool". It is know as "Blend Tool" in GIMP. We have to select two color for gradient fill. Then using the tool mentioned above we will fill the selection. The output will look similar to this -


7) So far we have completed the shape of the button. It is now time for to put some text. Select the "Text Tool" (T) and click on the button to enter text. The text itself will appear as a different layer. So you do not have to create a new layer for the text.

8) Adjust the text as per your need by using the "Move tool" (M). Now we are gonna add the shadow of the text. For this we need to duplicate the text. Select the text and open the Layer dialog box (CTRL+L) right click the text layer and click the duplicate layer option.


9) Double click the layer name to rename it. Rename the new duplicate layer into an understandable name. Now select the new renamed layer, and move it down. Put it just under the text layer. This newly created layer will be acting as shadow for the old text layer. So, the layer should be immediate below of the text layer.


10) Now select the text layer and click the "eye" on the left of the layer. This will hide the layer. Now you can edit the shadow layer. We need the shadow layer text to be a different color. In precise we need to define the shadow color. So, select the "Text Tool" and click on the text of the shadow layer. Make sure the shadow layer is selected. Change the color of the text to your desired shadow color.


11) Now we have to place the shadow in proper position. The layer should be moved slightly to the desired shadow direction. We have to move the shadow layer just a little to the left and down direction to create an optical illusion of drop shadow of the original text. Select the shadow layer and select the "Move Tool" (M) from the tool box. Now select the stage and press left and down twice. This will move the shadow layer just a bit in the left and down direction.


12) Now set the text layer to visible. This is done by clicking the "eye" of the text layer in the layer dialog.


13) As you can see a nice and cool looking button is created with shadow effect :) . We are just a little tweak away from using the button. Select the background layer bn_bg. Go to stage and then go to Image->Autocrop Image from the menu. This will make the button compact. Now we can export the button into different format and use it on our website :) .



Here is the total work.
If you have any suggestion or question, leave a comment.

Wednesday, April 14, 2010

HTML tweak: Use Image as submit button with rollover effect

We sometime need to submit form in our websites. To perform submit there is a HTML element name submit button. But what if we want to use image as a submit button? This can be done very easily. Let us see how it is done -

What we need :
  1. Image which will be acting as the submit button.
  2. Slightly modified Image of the first one to show some rollover effect.
  3. HTML codes and some JS code.
To use an image as a submit button we need the html tag <input> but the type property of the input tag will be image instead of submit. That way we can add an image as a button.

<input type="image" src="subscribe.png" />
This HTML code uses the subscribe.png as the submit button.
Now we will add some simple rollover effect.
<input type="image" src="subscribe.png" onmouseover="this.src='sub_top.png'" onmouseout="this.src='subscribe.png'"/>
 We are using small javascript code to change the image of the button whenever the user put the mouse over the button. This adds a nice rollover effect. We added the onmouseover event and then change the image src property of that element. We have to restore the image whenever the button loses focus. This is done by the onmouseout event.

All done. Here is the screen shot of how it looks.



Here is the total work.
If you have any suggestion or question please leave a comment.

Thursday, April 8, 2010

Rapid jQuery: HTML Form Validation

I have showed the idea of basic form validation with jQuery on my previous post. Now I am gonna show you guys how to speed up the validation process by using plug-in. Be ready to be amazed !

What we need :
  1. jQuery 
  2. jQuery Form Validation plug-in
  3. HTML codes :)
First we need to add the jQuery and the plug-in to our webpage which we want to validate.
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>
Now lets have a look at the form which has to be validated.

<form action="submit.php" method="post" id="doit" >
<fieldset>
    <label for="name">Name</label><br />
    <input type="text" id="name" name="name" class="required" minlength="2" /><br />
    <label for="email">Email</label><br />
    <input type="text" name="email" id="email" class="required email" /><br />
    <label for="zip_code">Zip code</label><br />
    <input type="text" name="digits" id="zip_code" class="required digits" /><br />
    <input class="submit" type="submit" value="Submit" />
</fieldset>
</form>
We have to set up some meta data in order to use the built in validation methods. We are using the label to notify the user about the field and also to display the error message. The important part is the for property. It is the same as the id of the component it is representing.
The next important part is the name property it must be one of the predefined class. some of the predefined classes are:
  • name - validation for common name
  • email - validation for email addresses
  • url - validation for url addresses
  • digits - validation for only digits
There are many predefined class. You can check the plug-in's documentation for complete list.
Next important property is class property. You can define your field to be required in the class property.
Note that the email input type has a class value of "required email". It means that the field is a necessary one and it must contain a valid email address.

Hope you have understand the basic behind the validation plug-in. Now we are only one step away from the validation process. Lets check it out -

<script type="text/javascript">
    $(document).ready(function () {
        $("#doit").validate();
    });
</script>
 Now we have to call the validate() method of the form. so we use the $("#doit") to select the whole form. And then call the validate() method to validate it.
Yes the validation is completed. Don't believe me? Why don't you just try it out.

Lastly you can add customization in the CSS section to change the way the message appears.
<style>
    label.error {
        color:#FF0000
    }
</style>
Here is a snapshot of the validation process :


Update - Here is the source code.
 If you have any suggestion or question, please let me know.

Monday, April 5, 2010

Do it with jQuery: HTML Form validation - Source @ Bottom

This is my follow up on my previous post on Form validation with javascript.
This post for those who want to try the form validation with jQuery.

jQuery is a javascript library developed for rapid application development. I,e - One can write less code by using it, so the development of the application is accelerated.

You can learn more about jQuery here.

To get started we need -
  1. HTML page which contains the form.
  2. jQuery Library
  3. Some jQuery codes.

After getting the jQuery libarary we have to add it to our HTML page. Scripts are generally added with in the <head></head> html tags.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<link type="text/css" href="style.css" rel="stylesheet" />
As you can see that this is done by using a <script> tag. We are gonna use the stylesheet (CSS) to decorate the messages. This will increase the user interactivity.


Now we need the html form which has to be validated.
<body>
<form action="submit.php" method="post">
<table cellpadding="0" cellspacing="0">
<tr><td>
First name: </td><td><input type="text" name="fname" id="fname" /></td><td>
<label id="s_fname"></label>
</td></tr>
</table>
</form>
We need the id field to get the component's handler so that we can manipulate it. Id provides a way to uniquely identify the component.

We now write a little code to register jQuery events with callback functions. All these code goes inside the <head></head> HTML tag.
<script type="text/javascript">
        $(document).ready( function() {
        $("#fname").blur(function () {
jQuery starts now. jQuery uses callback function to handle various event. One of the most import callback is the $(document).ready( function () {} );. When the page loads completely this event is raised. So, in the process of handling we can register more callback function. As we are dealing with the textbox, so we are gonna register the callback function for blur() event. When ever the text box loses focus this event is raised.
So, by registering callback method to it we can check the value of it and decide whether it is valid or not. We uses $(id) to get the component. Then we use the blur(fn) event to register the callback method.

Now we get the value from the textbox and examine it.
            var value = $("#fname").val();
            value = jQuery.trim(value);
            $("#fname").val(value);
First line gets the value of the component by calling the val() method. Then we use a jQuery utility function jQuery.trim(str) to trim the beginning and trailing whitespaces from the input. Then by the third line we again set the new value back to the textbox by using the val(value) method of the component.
            if (value == "" || value == null) {
                $("#s_fname").text("Please enter a name.");
                $("#s_fname").removeClass("valid");
                $("#s_fname").addClass("error");
                $("#fname").removeClass("valid_back");
                $("#fname").addClass("error_back");
            } else {
                $("#s_fname").text("Ok");
                $("#s_fname").addClass("valid");
                $("#s_fname").removeClass("error");
                $("#fname").removeClass("error");
                $("#fname").addClass("valid_back");
            }
        });
      
    });
  
</script>
We check the value for empty or null string. If the value of the textbox is either null or empty ("") then the value is invalid and we notify the user by setting the background of the textbox to red. We also display a red text to notify the user about the error. This is done by using the text(str) method of the component. text(str) sets the text of a component. We use removeClass(class name) and addClass( class name ) to remove and add the visual effect to the textbox defined in the CSS class. Here in the code "valid" and "error" are two CSS class. We use "valid" class to denote that the validation is successful and we use the "error" class to notify user that validation failed.

We now need to code the style.css file. This file contains the CSS class which we have used.

.error {
color:#FF0000;
}

.valid {
color:#006600;
}

.error_back {
background-color:#FF0000;
}

.valid_back {
background-color:#006600;
}
 Every class in the CSS must have a 'dot' (.) before them. In the class definition, we set the color value to red in the error class and we set the color value to greenish in the valid class. These classes are used to show message in red or green color to notify the user. We assign then depending upon the validation of the textbox.

The next to classes are used to change the background-color of the textbox. If the validation succeed then we set it to greenish other wise we set it to red to indicate that validation has failed.

We are all done. This post only shows how to use the jQuery functions for form validation. For a basic form validation you can see the previous post. Here is a snapshot of how it looks -

Update - Here is the source code.
If you have any question or suggestion, please let me know.

Saturday, April 3, 2010

Code n Learn: Form Validation Javascript

We all know that it is the programmer's duty to validate the form against invalid inputs. This checking or validation can be down in two ways. One is Client side, other is Server side.

We will have a quick review on how to validate form in client side using javascript.

Let us consider we have a form with first name, last name, email address and comment.

<form action="submit.php" method="post">
    First name: <input type="text" id="fname" value="" name="fname" /><br />
    Second name:<input type="text" id="lname" value="" name="lname" /><br />
    Email: <input type="text" id="email" value="" name="email" /><br />
    Comment: <input type="text" id="com" value="" name="com" /><br />
     <input type="submit" value="Submit" name="submit" onclick="return validate()" />
</form>
Ok, you may wonder why we add the id to all of the input type? Ids must be unique and we can search a component by its Id. So, we need to have an Id for each field which we will validate.
On the submit button we added onclick="return validate()". Here validate() is the form validation function. Then why we use return in front of it? Its because if the function return false then the form wont be submitted, It will be submitted once it receives true from validate function.

Now we add some basic style using CSS (Cascading Style Sheets). We only need two classes. One when there is a validation failed, other one is when validation is successful.

.error {
    background-color:rgb(255,0,0); /* red color */
}

.valid {
    background-color:rgb(0,255,0);  /* green color */
}
 We assign the error class when validation fails, thus making the component go red indicating an error was detected. You can run you imagination wild when customizing the class. We assign the other when validation success.

Now we only require the validation function to validate the form.
We need to get the handler of the First name & Last name text box. This can be done by searching the element by document.getElementById() function. Then we check the value entered by the user using the value property of that component.
function validate_component(name) {
     var comp = document.getElementById(name);
     if (comp.value == null || comp.value == '' ) {
         comp.className = 'error';      /* assign the css class to this component to indicate validation failure */
         return false;
     } else {
         fname.className = 'valid';    /* valid */
         return true;
     }
}
 We have setup the basic validation method. With this method we can validate first name, last name and comment component. We need to consider the email validation case. Cases to be considered when validating an email are -
  1. Email must have one '@' [at] and at least one '.' [dot]  ( xyz@yyy.ccc )
  2. '@' [at] cannot appear as first element  ( @xyzyyy.ccc )
  3. '.' [dot] cannot appear as last element  ( xyz@yyyccc. )
  4. Last '.' [dot] must be after '@' [at] but not immediate after ( x.y.z@yyy.ccc | x.y.z@.yyyccc )
  5. There can be exactly one '@' [at]
 Now the validation

function validate_email() {
    var error_occured = false;
    var e = document.getElementById('email');
    var email = e.value;
    error_occured = !validate_component('email');   /* check for basic validation */
    var at_index = email.indexOf('@');      /* returns the index of @  or -1 indication there was none */
    var at_last_index = email.lastIndexOf('@');
    var dot_index = email.lastIndexOf('.');
    if ( at_index == 0 || at_index == -1 || at_index != at_last_index || dot_index <= at_index || dot_index - at_index == 1 || dot_index == -1 || email.length - dot_index == 1 ) {
         error_occured = true;
         e.className = 'error';
    } else {
         e.className = 'valid';
    }
    return !error_occured; 
}
 What does what :
  1. at_index == 0 [ '@' was the first element so invalid ]
  2. at_index == -1 [ '@' was not found ! ]
  3. at_index != at_last_index [ There were more than one '@' (invalid) because first @ and last @ have different index number ]
  4. dot_index <= at_index [ '.' was infornt of '@' (invalid) ]
  5. dot_index - at_index == 1 [ '.' was immediately after '@' (invalid) ]
  6. dot_index == -1 [ '.' not found ! ]
  7. email.length - dot_index == 1 [ '.' is the last element (invalid) ]

Now we are ready to integrate all of this to one function.

function validate() {
            /* evaluate values */
    var ev_f_name = validate_component('fname');
    var ev_l_name = validate_component('lname');
    var ev_com = validate_component('com');
    var ev_email = validate_email();
    if ( ev_f_name && ev_l_name && ev_com && ev_email ) {
           return true;
    } else {
           alert('Please fill the form completely and correctly');
           return false;
    }
}
Here you go. The validation is complete. Hope you find it useful. If any suggestion or question please leave a comment.

Wednesday, March 31, 2010

Manage Multiple Network Interface Card in Win 7

You can change the order of your network cards in win 7. This can be done very easily. Here how it is done -
1. Go to Control Panel->Network and Internet->Network and Sharing Center. Now click the Change adapter settings from left side of the window.




2. You will see the connections along with your network cards. Hold down the Alt key. This will bring up the menu bar. Go to Advanced->Advanced Settings.



3. You will see your network showing in a list. There you can move up and down. Moving up an interface will make it more preferable by the system than the interface listed below it.



Hope this article is useful for you. If you have any suggestion or question please leave a comment.

Tuesday, March 30, 2010

CooL & Sexy yet Easy Message Box using jQuery

With the advent of Web 2.0 the website now gotten more interactive. Now a days website are elegant in looks. And it really hurts (hard works) to create a nice interactive website. jQuery grants us the wish - "write less do more".

jQuery is very easy to learn and implement. Today I am gonna show you how to add a jQuery UI component easily to your website.

First of all let us first see what do we need. We need the jQuery UI component.
Secondly, you need an editor to edit and write your website.
Lastly, you need some hard works.

After downloading first extract the zip file and go to the following directory -
jquery-ui-1.7.2.custom\development-bundle\ui
Now as we are going to work with only dialog (jQuery know them as dialog) so we only need some part of the total ui system. These are -
  • ui.core.js
  • ui.draggable.js
  • ui.resizable.js
  • ui.dialog.js
Why do we need these? Well they are pretty much self explained. We need the core by default. We are making our message box draggable and resizable. And lastly we need the specific dialog component.

We also need to add the jquery-1.3.2.min.js and jquery.bgiframe.js.

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="js/ui.core.js"></script>
    <script type="text/javascript" src="js/ui.draggable.js"></script>
    <script type="text/javascript" src="js/ui.resizable.js"></script>
    <script type="text/javascript" src="js/ui.dialog.js"></script>
    <script type="text/javascript" src="js/jquery.bgiframe.js">
</script>

Now we are going to use built in CSS style for the dialog box.
<link type="text/css" href="ui.all.css" rel="stylesheet" />

These are the basic requirements to use the dialog box. Now that we are ready, lets roll.
The message box looks like this -




Actually we create the message box using the html tag <div> . An example -
<div id="dialog" title="here goes your title" style="visibility:hidden">
    <p>here goes your message</p>
</div>
This div is hidden so normally we cant see it when the page loads. Now our last task is to assign the jQuery event such that whenever a page loads the message pops up automatically.

This is done like this -
<script type="text/javascript">
    $(function() {
                    $("#dialog").css("visibility:visible");
        $("#dialog").dialog({
            bgiframe: true,
            height: 600,
            width: 1000,
            modal: true,
            buttons: {
                Ok: function() {
                    $(this).dialog('close');
                }
            }
        });
    }); 
</script>
The first line is the $(function () {}); When the page loads this function is called. So, all other code must reside with it.
the second line contains $("#dialog").css("visibility:visible"); The #dialog finds the element whose id is dialog (that is of course our message div we have created earlier). We now sets the CSS value to visible because now we want the user to see the message box.
The next line creates the dialog box along with height, width and buttons. If you want the message box to be modal (which is most of the cases is) we have to set it to true.

Next step -  just joking. All done. Just refresh your webpage. Amazing, isn't it?
If any question or suggestion please leave a comment. Thanks.

Monday, March 29, 2010

Your Ultimate You Tube & Flash video (.flv) downloader

You liked someones video post at You Tube, now you want to download it. Alas! You Tube does not allow any direct link for downloading the content !!
Don't worry all you need is a set of tools.

The first tool you need is a You-Tube video grabber add-on. There are many add-on available to choose from. One of them is -Keep Tube
It allows you to download the flash video file (.flv) from you-tube like websites to your computer. Download and install it.

The next needed tool is Flash Got. It is a very popular add-on. It allows to crawl the whole website and download all the links and files from that website. It can also redirect download to your favorite download manager. Here you can find Flash Got.
https://addons.mozilla.org/en-US/firefox/addon/220

Third step requires the configuration of the flash got add-on. Here how it is done -
First open the flash got option from Tools->Flash Got-> More Options.



Now in the General Tab check the Download Manager Option and select your favorite download manager.
Also check the option Alt+Click = FlashGot if you like more control over your downloads.



Now you are all set to download .flv files from any site!
Lets see how it is done. Find any you tube video which you want to download.
Check the lower left side of your browser it should be dark-green other than faint-green.




This will pass the download link of the video file to your favorite download manager.
You can also download the video file by clicking here -



Hope this blog is useful to you. If you liked the blog or any suggestion please leave a comment. See you soon.