Get Tag With Post ID In WordPress

Today i was writing my plugin and required each post tag to be placed into a variable outside of WordPress loop. I have a look at WordPress function reference api and did some Google and surprisingly i couldn't find it. After a long time of digging on Google, i finally found a clue. Apparently, the method get_the_tags takes in a post id! However, if you look at get_the_tags reference page, it doesn't mention at all. Hence, i decides to write it down here to ease people life in the future.

Get Tag In WordPress

Once you get hold of your Post ID you can easily retrieve the tag associated with the post with the following code.

			$postid = $post->ID;
			get_the_tags($postid);

It will return a list of tags. Hope it helps šŸ™‚

Remove WordPress Admin Menu Without Affecting WordPress Core System

In WordPress, each user type have different capability. Sometimes, we want to change these capability and the most easiest way to do that is to remove what they can see when they logged in. Especially when someone wants to change WordPress into a powerful CMS and remove certain admin menu without touching the core system. In most CMS, there are so much restriction on their core system that makes it really inflexible. Unlike other system, WordPress is able to modify their core codes using plugin without affecting the fundamental codes in WordPress. Hence, we can continue to upgrade our system without having to worry about updates that will kill your modification. In this article, i will show you how i remove WordPress admin menu using plugin style without affecting WordPress Core codes.

WordPress Admin Menu

If you are able to dig into WordPress code, you will notice that their menu is created by a single function using two global variables as parameter. You can easily find this code located at wp-admin/menu-header.php, line 157-158.

_wp_menu_output( $menu, $submenu );
do_action( 'adminmenu' );

From the look of the method, you would have easily guess that this method is also a global method which takes in global variables $menu and $submenu to construct a full flag admin menu in WordPress. However, this method is like a loop that takes in a variable and loop through whatever is contain in the variable given. Hence, we will have to look at how each global variable is built to determine how to properly remove a WordPress admin menu.

Global Variable - $menu

If you dig deeper into WordPress, you will notice that the global variable $menu and $submenu are located at wp-admin/menu.php, line 25 onwards. This two variables play an important part in our objective as they create and remove main and submenu in WordPress. If you look at the code from line 28-115, you will notice that both menu and submenu is constructed first regardless of permission.

$menu[0] = array( __('Dashboard'), 'read', 'index.php', '', 'menu-top', 'menu-dashboard', 'div' );

$menu[4] = array( '', 'read', 'separator1', '', 'wp-menu-separator' );

$menu[5] = array( __('Posts'), 'edit_posts', 'edit.php', '', 'open-if-no-js menu-top', 'menu-posts', 'div' );
	$submenu['edit.php'][5]  = array( __('Edit'), 'edit_posts', 'edit.php' );
	/* translators: add new post */
	$submenu['edit.php'][10]  = array( _x('Add New', 'post'), 'edit_posts', 'post-new.php' );

	$i = 15;
	foreach ( $wp_taxonomies as $tax ) {
		if ( $tax->hierarchical || ! in_array('post', (array) $tax->object_type, true) )
			continue;

		$submenu['edit.php'][$i] = array( esc_attr($tax->label), 'manage_categories', 'edit-tags.php?taxonomy=' . $tax->name );
		++$i;
	}

	$submenu['edit.php'][50] = array( __('Categories'), 'manage_categories', 'categories.php' );

$menu[10] = array( __('Media'), 'upload_files', 'upload.php', '', 'menu-top', 'menu-media', 'div' );
	$submenu['upload.php'][5] = array( __('Library'), 'upload_files', 'upload.php');
	/* translators: add new file */
	$submenu['upload.php'][10] = array( _x('Add New', 'file'), 'upload_files', 'media-new.php');

$menu[15] = array( __('Links'), 'manage_links', 'link-manager.php', '', 'menu-top', 'menu-links', 'div' );
	$submenu['link-manager.php'][5] = array( __('Edit'), 'manage_links', 'link-manager.php' );
	/* translators: add new links */
	$submenu['link-manager.php'][10] = array( _x('Add New', 'links'), 'manage_links', 'link-add.php' );
	$submenu['link-manager.php'][15] = array( __('Link Categories'), 'manage_categories', 'edit-link-categories.php' );

$menu[20] = array( __('Pages'), 'edit_pages', 'edit-pages.php', '', 'menu-top', 'menu-pages', 'div' );
	$submenu['edit-pages.php'][5] = array( __('Edit'), 'edit_pages', 'edit-pages.php' );
	/* translators: add new page */
	$submenu['edit-pages.php'][10] = array( _x('Add New', 'page'), 'edit_pages', 'page-new.php' );

$menu[25] = array( sprintf( __('Comments %s'), "<span id='awaiting-mod' class='count-$awaiting_mod'><span class='pending-count'>" . number_format_i18n($awaiting_mod) . "</span></span>" ), 'edit_posts', 'edit-comments.php', '', 'menu-top', 'menu-comments', 'div' );

$_wp_last_object_menu = 25; // The index of the last top-level menu in the object menu group

$menu[59] = array( '', 'read', 'separator2', '', 'wp-menu-separator' );

$menu[60] = array( __('Appearance'), 'switch_themes', 'themes.php', '', 'menu-top', 'menu-appearance', 'div' );
	$submenu['themes.php'][5]  = array(__('Themes'), 'switch_themes', 'themes.php');
	$submenu['themes.php'][10] = array(__('Editor'), 'edit_themes', 'theme-editor.php');
	$submenu['themes.php'][15] = array(__('Add New Themes'), 'install_themes', 'theme-install.php');

$update_plugins = get_transient( 'update_plugins' );
$update_count = 0;
if ( !empty($update_plugins->response) )
	$update_count = count( $update_plugins->response );

$menu[65] = array( sprintf( __('Plugins %s'), "<span class='update-plugins count-$update_count'><span class='plugin-count'>" . number_format_i18n($update_count) . "</span></span>" ), 'activate_plugins', 'plugins.php', '', 'menu-top', 'menu-plugins', 'div' );
	$submenu['plugins.php'][5]  = array( __('Installed'), 'activate_plugins', 'plugins.php' );
	/* translators: add new plugin */
	$submenu['plugins.php'][10] = array(_x('Add New', 'plugin'), 'install_plugins', 'plugin-install.php');
	$submenu['plugins.php'][15] = array( __('Editor'), 'edit_plugins', 'plugin-editor.php' );

if ( current_user_can('edit_users') )
	$menu[70] = array( __('Users'), 'edit_users', 'users.php', '', 'menu-top', 'menu-users', 'div' );
else
	$menu[70] = array( __('Profile'), 'read', 'profile.php', '', 'menu-top', 'menu-users', 'div' );

if ( current_user_can('edit_users') ) {
	$_wp_real_parent_file['profile.php'] = 'users.php'; // Back-compat for plugins adding submenus to profile.php.
	$submenu['users.php'][5] = array(__('Authors & Users'), 'edit_users', 'users.php');
	$submenu['users.php'][10] = array(__('Add New'), 'create_users', 'user-new.php');
	$submenu['users.php'][15] = array(__('Your Profile'), 'read', 'profile.php');
} else {
	$_wp_real_parent_file['users.php'] = 'profile.php';
	$submenu['profile.php'][5] = array(__('Your Profile'), 'read', 'profile.php');
}

$menu[75] = array( __('Tools'), 'read', 'tools.php', '', 'menu-top', 'menu-tools', 'div' );
	$submenu['tools.php'][5] = array( __('Tools'), 'read', 'tools.php' );
	$submenu['tools.php'][10] = array( __('Import'), 'import', 'import.php' );
	$submenu['tools.php'][15] = array( __('Export'), 'import', 'export.php' );
	$submenu['tools.php'][20] = array( __('Upgrade'), 'install_plugins',  'update-core.php');

$menu[80] = array( __('Settings'), 'manage_options', 'options-general.php', '', 'menu-top', 'menu-settings', 'div' );
	$submenu['options-general.php'][10] = array(__('General'), 'manage_options', 'options-general.php');
	$submenu['options-general.php'][15] = array(__('Writing'), 'manage_options', 'options-writing.php');
	$submenu['options-general.php'][20] = array(__('Reading'), 'manage_options', 'options-reading.php');
	$submenu['options-general.php'][25] = array(__('Discussion'), 'manage_options', 'options-discussion.php');
	$submenu['options-general.php'][30] = array(__('Media'), 'manage_options', 'options-media.php');
	$submenu['options-general.php'][35] = array(__('Privacy'), 'manage_options', 'options-privacy.php');
	$submenu['options-general.php'][40] = array(__('Permalinks'), 'manage_options', 'options-permalink.php');
	$submenu['options-general.php'][45] = array(__('Miscellaneous'), 'manage_options', 'options-misc.php');

Furthermore, its being done neat and nicely. After that a few loop is conducted to remove the menu and submenu according to the user permission. You can see that on line 152 - 209.

$_wp_submenu_nopriv = array();
$_wp_menu_nopriv = array();
// Loop over submenus and remove pages for which the user does not have privs.
foreach ( array( 'submenu' ) as $sub_loop ) {
	foreach ($$sub_loop as $parent => $sub) {
		foreach ($sub as $index => $data) {
			if ( ! current_user_can($data[1]) ) {
				unset(${$sub_loop}[$parent][$index]);
				$_wp_submenu_nopriv[$parent][$data[2]] = true;
			}
		}

		if ( empty(${$sub_loop}[$parent]) )
			unset(${$sub_loop}[$parent]);
	}
}

// Loop over the top-level menu.
// Menus for which the original parent is not acessible due to lack of privs will have the next
// submenu in line be assigned as the new menu parent.
foreach ( $menu as $id => $data ) {
	if ( empty($submenu[$data[2]]) )
		continue;
	$subs = $submenu[$data[2]];
	$first_sub = array_shift($subs);
	$old_parent = $data[2];
	$new_parent = $first_sub[2];
	// If the first submenu is not the same as the assigned parent,
	// make the first submenu the new parent.
	if ( $new_parent != $old_parent ) {
		$_wp_real_parent_file[$old_parent] = $new_parent;
		$menu[$id][2] = $new_parent;

		foreach ($submenu[$old_parent] as $index => $data) {
			$submenu[$new_parent][$index] = $submenu[$old_parent][$index];
			unset($submenu[$old_parent][$index]);
		}
		unset($submenu[$old_parent]);

		if ( isset($_wp_submenu_nopriv[$old_parent]) )
			$_wp_submenu_nopriv[$new_parent] = $_wp_submenu_nopriv[$old_parent];
	}
}

do_action('admin_menu', '');

// Remove menus that have no accessible submenus and require privs that the user does not have.
// Run re-parent loop again.
foreach ( $menu as $id => $data ) {
	// If submenu is empty...
	if ( empty($submenu[$data[2]]) ) {
		// And user doesn't have privs, remove menu.
		if ( ! current_user_can($data[1]) ) {
			$_wp_menu_nopriv[$data[2]] = true;
			unset($menu[$id]);
		}
	}
}

Now we have a basic understanding of how WordPress handle their admin menu according to user access. We are ready to remove or modify any user access to alter WordPress user capability to view a particular menu in WordPress.

Removing WordPress Admin Menu

After having you wasting your time reading all the way from the top to here, i finally getting back to track and write what this article is about. We understand from all the rubbish on top that the global variable $menu array contains all the top level menu item and the global variable $submenu array contains all submenu page of each top level menu item. We can perform a few methods to remove a WordPress Admin Menu. The first simple and very basic way of removing a WordPress admin menu is to unset the menu resist in the global array.

function remove_submenu() {
global $submenu;
//remove Theme editor
unset($submenu['themes.php'][10]);
}

function remove_menu() {
global $menu;
//remove post top level menu
unset($menu[5]);
}
add_action('admin_head', 'remove_menu');
add_action('admin_head', 'remove_submenu');

We can remove a set of admin menu by doing this.

function remove_menus () {
global $menu;
		$restricted = array(__('Dashboard'), __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins'));
		end ($menu);
		while (prev($menu)){
			$value = explode(' ',$menu[key($menu)][0]);
			if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
		}
}
add_action('admin_menu', 'remove_menus');

The above code can be further reduce by 4 lines but i will keep it as it is.

This is pretty simple but not all user have these access and you might want to do some checking before accessing an invalid array to be unset which might give an error to be display. Although this is simple and the objective is achieve by removing the display of the menu/submenu, the user will still be able to direct access via the url. Hence, we need something better. Something that will disable all admin menu and sub menu tab from accessing and viewing.

function remove_menus () {
global $menu, $submenu, $user_ID;
	$the_user = new WP_User($user_ID);
	$valid_page = "admin.php?page=contact-form-7/admin/admin.php";
	$restricted = array('index.php','edit.php','categories.php','upload.php','link-manager.php','edit-pages.php','edit-comments.php', 'themes.php', 'plugins.php', 'users.php', 'profile.php', 'tools.php', 'options-general.php');
	$restricted_str = 'widgets.php';
	end ($menu);
	while (prev($menu)){
		$menu_item = $menu[key($menu)];
		$restricted_str .= '|'.$menu_item[2];
		if(in_array($menu_item[2] , $restricted)){
			$submenu_item = $submenu[$menu_item[2]];
			if($submenu_item != NULL){
				$tmp = $submenu_item;
				$max = array_pop(array_keys($tmp));
				for($i = $max; $i > 0;$i-=5){

					 if($submenu_item[$i] != NULL){
						$restricted_str .= '|'.$submenu[$menu_item[2]][$i][2];
						unset($submenu[$menu_item[2]][$i]);
					}
				}
			}
			unset($menu[key($menu)]);
		}
	}
	$result = preg_match('/(.*?)\/wp-admin\/?('.$restricted_str.')??(('.$restricted_str.'){1})(.*?)/',$_SERVER['REQUEST_URI']);
	if ($result != 0 && $result != FALSE){
		wp_redirect(get_option('siteurl') . '/wp-admin/' . $valid_page);
		exit(0);
	}
}
add_action('admin_menu', 'remove_menus');

The above function did just the thing. We will only required to provide the file name of the top level category and it will automatically disable all access to the subsequence admin sub menu. However, we will have to provide a valid page for user to gain access for the first time. The above code will disable ALL ADMIN MENU AND SUB MENU FOR ALL WORDPRESS ACCESS. The only page that was left accessible are the custom admin menu created by our user such as TweetMeme or Contact 7 form admin menu.

Easiest way to remove sub menu

After version 3.1, you are provided with the following methods to remove submenu

add_action( 'admin_menu', 'my_remove_menu_pages' );
function my_remove_menu_pages() {
        remove_menu_page('link-manager.php');
        //remove_menu_page('themes.php');
        remove_submenu_page( 'themes.php', 'themes.php' );
        remove_submenu_page( 'themes.php', 'theme-editor.php' );
        remove_submenu_page( 'themes.php', 'themes.php?page=custom-background' );
        remove_submenu_page( 'widgets.php', 'theme-editor.php' );
        remove_menu_page('tools.php');
        remove_menu_page('upload.php');
        remove_menu_page('edit-comments.php');
        remove_menu_page('plugins.php');
        remove_menu_page('admin.php?page=w3tc_general');
        remove_menu_page('admin.php?page=better_wp_security');
        remove_menu_page('admin.php?page=wpcf7');
        remove_submenu_page( 'index.php', 'update-core.php' );
        remove_submenu_page( 'options-general.php', 'options-discussion.php' );
        remove_submenu_page( 'options-general.php', 'options-writing.php' );
        remove_submenu_page( 'options-general.php', 'options-reading.php' );
        remove_submenu_page( 'options-general.php', 'options-permalink.php' );
        remove_submenu_page( 'options-general.php', 'options-media.php' );
}

Pretty simple and direct, first parameter is the file name or parent file name of the page you want to remove, second parameter is the submenu you wish to remove.

Concolusion

This is the way i use to remove admin menu in WordPress. We do not have to check for user access as the user will already be redirected to the specific page before they can enter the permission denial page. Have fun šŸ™‚

200++ Photoshop Photo Effects

Have you ever wonder where is that photo effect tutorial you saw the other day and start searching all over the internet but couldn't find what you saw initially? Honestly, i have. That is why i throw them all into this article instead. But i also use these article to gain inspiration on what to do with my photo image. Sometimes we are like a lost bird when it comes to creative design. Hence, putting up links of images can really benefit myself and hopefully people who come across this article too.

Create a Powerful Mental Wave Explosion Effect

wave-explosion

Photo to Pencil Sketch Effect

pencil

Sin City Style Effect

sincity

How To Make Your Own Vector Portraits

vector

Tutorial: Good and Evil Photo Effect

evil

The Making of Mystic Effect

mystic

Transform A Person Into An Alien Effect

alien-photoshop

Reflective Bubbles Effect

3315027133_4f9e8c8241

Crack and Peel Effect

3315027243_4fcabe071f

Expressive Lighting Effect

aura-effect

Displacement Effect

awesome-effect

Vector Composite Effect from a Photo

blabus

Easy Watercolor Painting Effect

cartoon-effect

Twins Effect

clones

Apple Style Portrait Effect

coldplay

Compositing Effect

compositing

Dimension Effect

dimension

Blue Glow Dreamy Effect

dreamy

Ink Drops in Your Digital Compositions Effect

dropink

Super Slick Dusky Lighting Effect

earth effect

Electrifying Energy Beams Effect

electric

Eery-Eye Photo Effect

evil-eye-effect

Fairy Night Eye Effect

Fairy-Night

Fairy tale Effect

fairytale

Make your image look awesome with a few light effects

fewlights

Fire Lines Effect

firelines

Make Perfume Commercial

fragrance

Dirty Grunge Effect

grunge

Coloring Effect

guitar-girl

Photoshop Effect: Focus With Light

hand-light-effect

Speeding Car Effect

car-effect

The Maiden and Hummingbird Photo Manipulation

doll-effects

Design an Epic Fantasy Scene with Photoshop

fantasy-effects

Thermal Photo Effect

flame-effects

Create an Abstract Design with Curved Light Streaks

hand-effect

Dance Photo Effect

hip-hop-effect

Glowing Neon Effect

human-3d-effects

Fantasy Art Scene

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvc2lsZW50by5qcGc=

Sexy Model with Glowing Bubbles Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy8xMHN0ZXBzMi5qcGc=

Glamour model

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9hZG9iZXR1dG9yaWFsei5qcGc=

Create an Amazing A.I. Robot Woman in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9kZXNpZ25yZXZpdmVyLmpwZw==

Impressive Photo Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9waG90b3Nob3A4eC5qcGc=

Make Perfect Selection for Human Object by Utilising Channel Mask Technique in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9wc2R2YXVsdC5qcGc=

Create a Realistic Break-Apart Effect with Debris Brushset in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9wc2R2YXVsdDIuanBn

Create sexy cyborg Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9wc2RlbHV4ZS5qcGc=

Create a Stylish Two-Tone Photo Montage Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9wc2RmYW4uanBn

Design a Stylish Fashion Advert Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9wc2RmYW4yLmpwZw==

Create a Divine Angel Montage Effect in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy90dXRvcmlhbDkyLmpwZw==

Text Image Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy90dXRvcmlhbHBhcmsuanBn

Dynamic Scene with a Fallen Angel Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy90dXRzcGx1czMuanBn

Combine Photo Elements to Create a Surreal Photo Manipulation Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9zaG9wdHV0b3JpYWxzLnBuZw==

Fairy and Sunset Landscape Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcHN3aXNoLmpwZw==

Photo Manipulation - Creating a Fantasy Scene

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcHNkcm9ja3N0YXIuanBn

The Soft Sea Light

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcHNkdG9wLmpwZw==

Awesome Fantasy Style Castle Scene Creation in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcHNkdmF1bHQuanBn

Fantasy Photo Manipulation Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvdHV0c3BsdXM0LmpwZw==

Fantasy Creature in a Misty Landscape

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvdHV0c3BsdXMuanBn

Create an Out of Bounds Fantasy Illustration Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvdHV0c3BsdXMyLmpwZw==

Making of a Forest Magical Scene

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvMTBzdGVwcy5qcGc=

Making of Urban Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvY2dhcmVuYS5qcGc=

Create a Magic Crystal Ball

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvYWRvYmV0dXRvcmlhbHouanBn

Warth Best Life

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvYWRvYmV0dXRvcmlhbHoyLmpwZw==

Fantastic Tree

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvYWxmb2FydC5qcGc=

Magic lamp in the old room

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvYWxmb2FydDIuanBn

Fantastic Water Landscape

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvYWxmb2FydDMuanBn

Matte painting

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvZXllc29udHV0b3JpYWxzLmpwZw==

Magic Book

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvZXllc29udHV0b3JpYWxzMi5qcGc=

Serenity Prayer

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvZXllc29udHV0b3JpYWxzMy5qcGc=

Galaxy Angel

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvZXllc29udHV0b3JpYWxzNC5qcGc=

Badass Bling Effect in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2dvbWVkaWF6aW5lLmpwZw==

Flying Girl in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2FiZHV6ZWVkby5qcGc=

Really cool Eclipse Effect in Photosho

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2FiZHV6ZWVkbzIuanBn

X-MEN movie poster

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2Fkb2JldHV0b3JpYWx6LmpwZw==

How to create a stylish mad lady in photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2Jlc3RwaG90b3Nob3B0dXRvcmlhbHMuanBn

Fantasy light effects in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2RpZ2l0YWxhcnRzb25saW5lMi5qcGc=

Lighting effects in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2RpZ2l0YWxhcnRzb25saW5lMy5qcGc=

Make incredible surreal images

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2RpZ2l0YWxhcnRzb25saW5lNC5qcGc=

Dazzling Dance Photo Manipulation Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL3Bob3Rvc2hvcHR1dG9yaWFscy5wbmc=

Light and Glow Effect In Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL3NlY29uZHBpY3R1cmUuanBn

Energize Your Graphics with Abstract Energy Lines

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL3R1dG9yaWFsOS5qcGc=

Ps Advanced Splatter Effect Tutorial

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL3R1dGNhbmR5LmpwZw==

Lighting Effect in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyLzEwc3RlcHMuanBn

Creative Photoshop Animal King Photo Manipulation Tutorial

anime-king-effects

Robotic Frog

frog

How to Create a Flying Land Illustration On Fire

knight-story-effects

Watercolor Effect

light-girl-effects

Alien Invasion

invasion-effects

Creating Energy Spheres

light-beam

Seriously Cool Photoshop Explosion Effect

light-effect

Lightning from hand

lighting-effects

Adding Light Streaks Effect To A Photo

lights

How To Make Circle Pixels Effect

lines-effect

Giving A Mafia-Look Effect

mafia

Design an Awesome Space Dancer Scene Effect

magic-effects

The Little Mermaid Photo Effect

mermaid

Design a wolf howling at the moon effect

midnight-effects

Light Effect On A Model

modern-effect

How To Turn Your Photo Into Movie-Like Effect

movie-effect

Dynamic Lightning Effect

building

Dark Art Picture Style Effect

night-effect

The Ocean Girl Photo Effect

ocean

How To Make Digital Photos Look Like Lomo Photography Effect

old-effects

Age Progression

old-lady-effect

Creating an Abstract Watercolor Effect

painting-effects

Fiery Photoshop Space Explosion Effect

planet-effect

Add Realistic Rainbow Effect To A Photo

ranbow-effect

Fantastic Disintegration Effect

rawr-effects

Realistic Water Reflection Effect

reflect-effect

Grunge Photo Edges Effect

shouting-effects

Add A Sparkle Trail Effect To A Photo

sparkle

How to Place a Use lighting effects to make photos sparkle

sparkle02

Creating Light Motion Trails & Glowing Sparks Effect

sparks

Christmas Fairy Magic Effect

star-effects

Bringing A Stone Statue To Life Effect

state-effects

How to Turn Humdrum Photos into Cinematic Portraits

storm-effects

Colorful Picture Style Effect

strong-impression

Realistic Tattoos Effect

tatoo-effect

Cool Halftone Effect

text-effect

How to make a Typographic, Retro, Space Face Effect

topology-effect

Photo Editing / Retouching

tragic

How to Apply Textures to Uneven Surfaces

tree-effects

Create a fantasy illustration in Photoshop

unicorn-effects

Urban-Style Piece Of Artwork

urban

Watchmen Effect

watchman-effects

Make an Apple Coldplay Style Ad in Photoshop

welcome-effect

Zombie Effect

zombie-effect

Halftone Dots And Linear Light

3315027899_4deff3e472

Beautiful Lady Effect

3315027947_3b5fe05642

Mosaic, Fill A Photo With Photos Effect

3315028177_dfda4429b6

Creating A Rocking Silhouette

3315028369_d29730bbd1

Make Photos More Suggestive

3315028409_7f18db32d7

Adding Reflections To Sunglasses Effect

3315028555_e6cf210930

Devil's Eye Effect

3315854678_0ee80c73ea

Fantasy Art

3315855042_3dd0fdbdb2

Retro Comic Book Effect

comic-effect

Water effect photo montage

wave

Vibrant Image Effect Using Photoshop

dance-effect

Ghost Effect

ghost

Dramatic gritty effect

Dramatic-gritty-effect

Photo to Illustration Effect

photo-to-illustrator

Turn A Photo Into A Collage Of Polaroids In Photoshop

Collage-Polaroids-Photoshop

Instant Photo To Oil Painting Action

Instant-Photo-To-Oil-Painting-Action

Photo to sketch Effect

soft-contrast-2

Pop Art Silkscreen Effect

pop-art-silkscreen-350

The Louis Daguerre Effect

daguerre-photo-effect-final

Cubism Effect

cubic-effect

Cross-Processing Effect

cross-effect

Create an Illustrated Look From a Photograph

photo-to-drawing

Super mysterious lighting effects for your image

sun-effect

HDR Effect Tutorial

HDR-tutorial

FAKE MODEL PHOTOGRAPHY EFFECT

fake-photography-effect

Photo to stencil Effect

Photo-to-stencil

Transform your Photos into a Beautiful Mosaic

picture-mosaic-14

Panoramas on Steroids Effect

panographyfeature

Pop Art Effect

Pop-Art

Filtering Out Colours

filter-color

City Globe Effect

city-global

Vintage photo effect

Vintage-photo-effect

Selective Sepia Effect

Selective-Sepia

Photoshop Rain Effect

photoshop-rain

Soft Glow Effects

slow-glow-effect

Charcoal Effect

charcoal-drawing-photoshop

High-Key B&W Portrait Effect

high-key01

Horror Film Effect

Horror-Film-Effect

Snow Effect

Snow-effect

HDR - High Dynamic Range Photography

HDR

English Tea can Painting Effect

English-Tea-can-Painting

Realistic Spotlight Effect in Photoshop

Realistic-Spotlight-Effect-Photoshop

Better negative effect

negative-effect

Dave Hill Look Effect

dave-hill-photoshop

Frosted Pixels Effect

Frosted-Pixels

Darklight Photomanipulation

Darklight-Photomanipulation

Blue Print Effect

blue-print-effect

PIXEL STRETCH EFFECT

pixel-stretch

OLD MOVIE EFFECT

old-movie

REALISTIC FOG & MIST EFFECT

realistic-fog-mist-effect

The Night Vision Thing Effect

night-vision-2

A Realist Painting Effect

realistic-painting

Hot & Fiery Photo Effect

Hot-Fiery-Photo-Effect

Trippy Colors Photo effect Tutorial

trippy_color_effect_preview

Digital Painting with Light

Digital-Painting-Light

Displacement Water Effect

Displacement-Water-effect

Creating a 3D effect with image editing software

3d-pop-out

India Movie Look

movie-look

Faking Depth Of Field Effect

Depth_Of_Field

Infrared Photo Effect

infraned-effect

Blurry TV Effect

blurry-tv-effect

PUZZLE PATTERN EFFECT

puzzle-effect

Face painting on cracked wall Tutorial

Face-on-Cracked-wall

Create photo mosaics effect

photo-mosaics

Bourne Ultimatum Color and Motion Blur Effect

Bourne-Ultimatum-Color-and-Motion-Blur

Cast Light From A Window Effect

window-light-effect

Stylized paint effect

Stylized-paint-effect

Night shooting effect

Night-shooting-effect

Give Your Photos a Color Ink Sketch Effect

Color-Ink-Sketch-Effect

Wicked Blast Effect

Wicked-Blast

Fix Perspective Effect

fix-perspective

Sharpen with Edge Mask

sharpen-edge

Making Your Subject Pop Out Of A Photo

photo-pop-out

Telling Stories With Shadows

superman

Digital Pixel Effect

digital-pixel

Tearing A Photo To Reveal Another

tear-effect

Worn, Torn Photo Edges Effect In Photoshop

photoshop-worn-torn-photo-edges

image-hard-light

Mirror Image Effect In Photoshop

photoshop-mirror-image-effect

Placing An Image Inside Of Another In Photoshop

tv-image

Create A Starry Sky In Photoshop

starry-sky

Photo Into a Beautiful Painting

tutorial-how-to-turn-a-photo-into-a-beautiful-painting-in-photoshop

 

Summery

Finally, this article has ended (after 200 tutorial i lost count). This really eats a lot of my time but i think it is worthwhile since i can refer back to it every single time and won't find myself in 'where's that tutorial again' situation. Nonetheless, if any of you are using this too, please throw in more photoshop photo effect tutorial that can benefit us all. Enjoy šŸ™‚

17 JavaScript Form Validation Snippets

Last week i wrote 25 form validation for PHP. I find useful to have more layer of defend as JavaScript might malfunction or disable and cause your validation to fail but the form is still being passed on to our server. Nonetheless, JavaScript validation does provide certain level of restriction and protection for any web application. Especially when web is evolving quickly in this period of time. We are required to validate any data from our user to prevent any harm that can cause damage to our application and businesses. These JavaScript form validation snippets are needed in every form validation and repeating searching for them is unnecessary and slow down development processes. Therefore, you might want to bookmark these snippets for your future needs

Email Validation

Email validation is the most basic validation that any web application would have.

function isEmail(elem, helperMsg){
	var regexp  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(regexp.test(elem.value)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var email = document.getElementById('ham_email');
if(isEmail(email, "Invalid Email Format")){
//proceed..
}

URL Validation

URL validation helps to validate whether a particular string is a valid url format.

function isUrl(elem, helperMsg) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	if(regexp.test(elem.value.toLowerCase())){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var link = document.getElementById('ham_link');
if(isUrl(link, "Invalid link")){
//proceed..
}

Username Validation

This function help us validate whether a username contain valid character and length. It accept any underscore, alphabets and numbers within 5-25 characters.

function isValidUsername(elem, msg) {
	var regx = /^[A-Za-z0-9_]{5,25}$/;
	if(regx.test(elem.value)){
		return true;
	}else {
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

You can add additional symbols or change the length of the validation easily by alter the regular expression.

In order to use this, we pass in an object and an alert value if it fail.

var username = document.getElementById('username');
if(isValidUsername(username, "Invalid character found on username!")){
//proceed...
}

Password Validation

Here is a simple password strength validation that check the following criteria.

  1. Passwords will contain at least 1 upper case letter
  2. Passwords will contain at least 1 lower case letter
  3. Passwords will contain at least 1 number or special character
  4. Passwords will contain at least 8 characters in length
  5. Password maximum length should not be arbitrarily limited
function isStrongPassword(elem, msg) {
	var regx = /(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/;
	if(regx.test(elem.value)){
		return true;
	}else {
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var password = document.getElementById('password');
if(isStrongPassword(password, "Your password fail the basic strength test. \n1. Passwords will contain at least 1 upper case letter\n2. Passwords will contain at least 1 lower case letter\n3. Passwords will contain at least 1 number or special character\n4. Passwords will contain at least 8 characters in length\n5. Password maximum length should not be arbitrarily limited\n")){
//proceed..
}

Numeric Validation

This validate whether a given string contain a valid numeric value which include both negative value and decimal ones.

function isNumeric(elem, helperMsg){
	var numericExpression = /^[-]?\d*\.?\d*$/;
	if(elem.value.toString().match(numericExpression)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var price = document.getElementById('price');
if(isNumeric(price, "Invalid value found")){
//proceed...
}

Text Empty Validation

In every form validation, there is always a need to check whether a particular text box is empty.

function isEmpty(elem, helperMsg){
	if(elem.value.toString().length > 0){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var name = document.getElementById('ham_company');
if(!isEmpty(name, "Please give us your name")){
//proceed...
}

Radio Box Validation

We can determine whether a radio box has been selected using this function.

function hasSelected(elem, msg){
	for (i = 0; i < elem.length; i++) //for all check boxes
	{
		if (elem[i].checked == true ) //otherwise elements also looks at radio buttons
		{
			return true;
		}
	}
	alert(helperMsg);
	elem[0].focus();
	return false;
}

Drop Down Validation

We also check whether a particular drop down box has its value selected with the following function.
In order to use this, we pass in an object and an alert value if it fail.

var radio = document.getElementById('radio');
if(hasSelected(radio, Please select your gender")){
//proceed...
}
function isSelected(elem, helperMsg){
	if(elem.options[elem.selectedIndex].value.toString().length > 0){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var month = document.getElementById('ham_month');
if(isSelected(month, "Please select a month")){
//proceed...
}

Check Box Validation

We can perform check box validation to see whether a particular check box has been selected through this function.

function hasChecked(elem, msg){
	for (i = 0; i < elem.length; i++) //for all check boxes
	{
		if (elem[i].checked == true ) //otherwise elements also looks at radio buttons
		{
			return true;
		}
	}
	alert(helperMsg);
	elem[0].focus();
	return false;
}

In order to use this, we pass in an object and an alert value if it fail.

var checkbox= document. getElementsByName('checkbox');
if(checkPhone(checkbox, "Please tick one of the check box")){
//proceed...
}

Phone Validation

This function will validate the following criteria phone number.

  • phone:
    339-4248
    339-42-48
    339 42 48
    339 4248
    3394248
    (095) #phone#
    (095)#phone#
    +7 (095) #phone#
    +7 (095)#phone#
    +7(095) #phone#
    +7(095)#phone#
function checkPhone(elem, msg)
{
	var str = elem.value;
	var phone2 = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
	if (str.match(phone2)) {
   		return true;
 	} else {
 		alert(helperMsg);
		elem.focus();
		return false;
 	}
}

In order to use this, we pass in an object and an alert value if it fail.

var phonenumber = document.getElementById('phonenumber');
if(checkPhone(phonenumber, "Invalid Phone Number")){
//proceed...
}

File Extension Validation

This function validate whether a particular upload string contains a valid extension.

function isAllowedFileExtension(elem, helperMsg){
	var alphaExp = /.*\.(gif)|(jpeg)|(jpg)|(png)$/;
	if(elem.value != "")
	{
		if(elem.value.toLowerCase().match(alphaExp)){
			return true;
		}else{
			alert(helperMsg);
			elem.focus();
			return false;
		}
	}
	else
		return true;
	return false;
}

In order to use this, we pass in an object and an alert value if it fail.

var upload = document.getElementById('ham_upload');
if(isAllowedFileExtension(upload, "Please Upload Gif, Png or Jpg Images Files Only")){
//proceed...
}

IP Validation

Sometimes there is a need to validate whether a particular IP address is valid using JavaScript.

function isValidIPAddress(elem, msg) {
   var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
   ipaddr = elem.value.toLowerCase();
   if (re.test(ipaddr)) {
      var parts = ipaddr.split(".");
      if (parseInt(parseFloat(parts[0])) == 0) { return false; }
      for (var i=0; i<parts.length; i++) {
         if (parseInt(parseFloat(parts[i])) > 255) { return false; }
      }
      return true;
   } else {
		alert(helperMsg);
		elem.focus();
		return false;
   }
}

In order to use this, we pass in an object and an alert value if it fail.

var ip= document.getElementById('ip');
if(isValidIPAddress(ip, "Invalid IP Address")){
//proceed...
}

US Social Security Number Validation

Testing US Social security number can be done with the below function.

function isValidSSN(elem, msg) {
	var value = elem.value.toLowerCase();
	var tmp = false;
    var re = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/;
    if (!re.test(value)) { tmp = true; }
    var temp = value;
    if (value.indexOf("-") != -1) { temp = (value.split("-")).join(""); }
    if (value.indexOf(" ") != -1) { temp = (value.split(" ")).join(""); }
    if (temp.substring(0, 3) == "000") { tmp = true; }
    if (temp.substring(3, 5) == "00") { tmp = true; }
    if (temp.substring(5, 9) == "0000") { tmp = true; }

	if(tmp){
		alert(helperMsg);
		elem.focus();
		return false;
	}else
    return true;
}

In order to use this, we pass in an object and an alert value if it fail.

var ssn = document.getElementById('ssn');
if(isValidSSN(ssn, "Invalid US Social Security Number")){
//proceed...
}

US Zip Code Validation

We can valid US zip code using the following function.

function isValidZipCode(elem, msg) {
   var re = /^\d{5}([\-]\d{4})?$/;
   var value = elem.value.toLowerCase();
   if(re.test(value)){
		return true;
   }else {
		alert(helperMsg);
		elem.focus();
		return false;
   }
}

In order to use this, we pass in an object and an alert value if it fail.

var zip= document.getElementById('zip');
if(isValidSSN(zip, "Invalid US Zip Code")){
//proceed...
}

Date Validation

This function validate date with a given format.

function isValidDate(dateStr, format) {
   if (format == null) { format = "MDY"; }
   format = format.toUpperCase();
   if (format.length != 3) { format = "MDY"; }
   if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || _
      (format.indexOf("Y") == -1) ) { format = "MDY"; }
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
      var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
   } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
   } else { // The year must be third
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
   }
   // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
   if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") { var mm = parts[0]; } else _
      if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; }
   if (format.substring(0, 1) == "D") { var dd = parts[0]; } else _
      if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; }
   if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else _
      if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; }
   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
   return true;
}

You will use the function this way,

if (!isValidDate(myDateString, "DMY")) { alert("The date is not in the correct format."); }

Time Validation

This function validate time such as

  1. 02:25AM
  2. 00:23PM
  3. 23:45PM
  4. 11:23
  5. etc.
function isValidTime(value) {
   var hasMeridian = false;
   var re = /^\d{1,2}[:]\d{2}([:]\d{2})?( [aApP][mM]?)?$/;
   if (!re.test(value)) { return false; }
   if (value.toLowerCase().indexOf("p") != -1) { hasMeridian = true; }
   if (value.toLowerCase().indexOf("a") != -1) { hasMeridian = true; }
   var values = value.split(":");
   if ( (parseFloat(values[0]) < 0) || (parseFloat(values[0]) > 23) ) { return false; }
   if (hasMeridian) {
      if ( (parseFloat(values[0]) < 1) || (parseFloat(values[0]) > 12) ) { return false; }
   }
   if ( (parseFloat(values[1]) < 0) || (parseFloat(values[1]) > 59) ) { return false; }
   if (values.length > 2) {
      if ( (parseFloat(values[2]) < 0) || (parseFloat(values[2]) > 59) ) { return false; }
   }
   return true;
}

Credit Card Validation

This function validate whether a given string format is similar to a credit card type.

function isValidCreditCard(type, ccnum) {
   if (type == "Visa") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "MC") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "Disc") {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "AmEx") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "Diners") {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   }
   if (!re.test(ccnum)) return false;
   // Remove all dashes for the checksum checks to eliminate negative numbers
   ccnum = ccnum.split("-").join("");
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0) return true; else return false;
}

Summary

Usually i will use these code in such a way to validate my form. I find it neat and tidy.

form.onsubmit = validation;
var validation = function(){
	var name = document.getElementById('ham_company');
	var email = document.getElementById('ham_email');
	var link = document.getElementById('ham_link');
	var description = document.getElementById('ham_desc');
	var banner = document.getElementById('ham_banner');
	var month = document.getElementById('ham_month');
	var url = document.getElementById('ham_url');
	var upload = document.getElementById('ham_upload');
	var quiz = document.getElementById('ham_quiz');
	if(isEmail(email, "Invalid Email Format"))
		if(isUrl(link, "Invalid link"))
			if(OneNotEmpty(url, upload, "Either image url or upload must be perform!"))
				if(isAllowedFileExtension(url, "Please provide an image with Gif, Png or Jpg extension Only"))
					if(isAllowedFileExtension(upload, "Please Upload Gif, Png or Jpg Images Files Only"))
						if(isSelected(month, "Please select a month"))
							if(isSelected(banner, "Please select a banner"))
								if(NotEmpty(quiz, "Please answer the quiz"))
									if(NotEmpty(name, "Please give us your name"))
									{
										return true;
									}

	return false;
}

On the other hand, you can always brings up new form validation snippets to share with me in this article. I will love to know šŸ™‚

Determine Whether JavaScript Is Enabled/Disabled Via PHP

Recently i was working on a project where there is a need to determine whether JavaScript is enabled or was disabled by the user. Depending whether the JavaScript is enable or not, the system will rely on JavaScript operation if it does and PHP operation if it doesn't. TheĀ fundamentalĀ solution to this is to detect whether JavaScript is enable before the system can determine which approach can be used. However, there is no easy solution to determineĀ whether a client scripting is enable in a server scripting language (PHP) without finish loading the page! Therefore, in this article we will discuss whether there is such possibility to use PHP to determine whether JavaScript is enabled for your web application.

The Problem

The main problem is that a server script language can never be able to determine whether a client script language is available as the server script language will always run first. Furthermore, the client script is always run on the client side and never executed on the server side. Therefore, when the server scripting is running at the server side and send to the client for display, the server scripting language will have no idea what is going on with the client environment. Hence, strictly speaking will be unable to determine JavaScript is enable or disable.

The Solution

Although it sounds impossible for server side to determine whether a client scripting is available such as JavaScript but certain tricks can be perform in order to achieve this. However, it won't be a convenient one. Recall that every web system should have a redirect index.php page to prevent our code from showing in plaintext if anything happen? We can use that page to determine whether javascript is enable by writing a script to either append a value and post over to the next page or a better alternative is to store it into the user cookie. If you store a value and post it to the next page, the validation can only occur within the main page. However, if you utilize cookie to determine whether JavaScript is available, you can always use php to determine whether that cookie value is available. If it is not available (they delete their browser cookie on the way) you can redirect that user to the index.php to revalidate JavaScript is enable. Once it is being verify, you will just show a message to the user after index.php has redirect or run on pure php.

On the index.php script, it will be something like this,

<script type='javascript/text'>
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
createCookie('verify_cookie', 'Y', 1);
</script>
<meta http-equiv="refresh" content="2;url=main.php?c=1">

We have a function that help us to create a cookie if JavaScript available. Once this is done, we redirect the user to main.php where our real page is located with a get value of c=1. This value is needed to avoid recursive request. We can't use PHP header function because it will redirect before JavaScript has the opportunity to run and the code should be placed before the head tag to make this valid. On all other pages we will have something like this before the header.

<?php
	//filter the global variable first.
	if(!isset($_COOKIE['verify_cookie']) && $_GET['c'] == 1){
		echo 'JavaScript is disable';
	}else if(!isset($_COOKIE['verify_cookie'])){
		//perform check to determine whether the cookie expire OR it really was disabled.
		header('location: index.php');
	}else{
		//perform another check on javascript similar to index.php if you afraid that the cookie exist but javascript was disabled.
	}
?>

The above is to verify whether javascript exist in each page and use to run either pure php or combination with JavaScript as these script can be imported using PHP if needed. The solution above can be use as a references and not necessary a solid solution.

Alternative Solution

The alternative solution to this is to use the noscript tag which is very simple and make your life a better place to live in.

<script>
document.getElementsByTagName('body')[0].innerHTML = 'JavaScript is enable.';
<script>
<noscript>
JavaScript is disabled.
<noscript>

Conclusion

Many will turn to noscript tag that can really ease and simplify the way we code. However, for some system which required to determine whether script is enabled for different server script to run. This might help those that are doing such approach as noscript tag will only run after the server has processed its information. On the other hand, you can combine this approach with the no tag approach to better validate your logic.