Pure Javascript form Validation Script now easy

Web developer comes in sitution of checking forms with simple javascript. Use following Pure Javascript form Validation Script make your life easy.

Many times we come to same problem which we faced so many times. But still when Web developer comes in sitution of checking forms with simple javascript. Use following Pure Javascript form Validation Script make your life easy.

Pure Javascript form Validation Script

He started looking into some solutions. Some people try to use the some third party JS library like (Mootools, Jquery, lightbox, Prototype and etc…)

I recommend not to use these JS library because these library will take some brandwidth of your website. Most of the code these JS library is useless or un useful to your website.
Still you are adding these JS library to your website.

In this article I will show you very easy technique to the javascript form validations with minium code.

Just copy paste the following code in to your head section first.


<script type="text/javascript">
// Set maxlength value for your required fields
var maxlength = 255;
/*
* You can pass three parameters this function
* Example : ValidateRequiredField(phone,"Telephone must be filled out!", "number");
* For string format no need to pass any strFormat.
*/
function ValidateRequiredField(field,alerttxt,strFormat) {
with (field) {
if (value == null|| value == "") {
field.style.background= "grey";
alert(alerttxt);return false;
} else if (value.length > maxlength ) {
field.style.background= "grey";
alert('Maxlenth should be not more than 255 charactor');return false;
} else if (strFormat == 'number' && isNaN(value) ) {
field.style.background= "grey";
alert(field.name + ' is not a number, Please put in Numric format');return false;
} else {return true;}
}
}

/*
* Using the function you can validate the email functions
* Example: ValidateEmailAddress(email,"Email is not in Valid format!")
* Return true or false
*/
function ValidateEmailAddress(field, alerttxt) {
with (field) {
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
if (apos < 1 || dotpos-apos < 2)
{alert(alerttxt);return false;}
else {return true;}
}
}

/*
* Using the function you can validate the checkbox in the form
* Example: ValidateCheckBox(agreement,"Agreement is not checked!")
* Return true or false
*/
function ValidateCheckBox(field,alerttxt) {
with (field) {
if (!field.checked == 1) {
alert(alerttxt);return false;
} else {return true;}
}
}

/*
* Using the function you can validate the checkbox in the form
* Example: ValidateRequiredField(website,"Website name is required!")
* Return true or false
*/
function ValidateWebAddress(field,alerttext) {
with(field) {

var companyUrl = value;

var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;

if(RegExp.test(companyUrl)) {
return true;
} else {
alert(alerttext);
return false;
}
}
}

function ValidateCompleteForm(thisform) {
with (thisform) {

if (ValidateRequiredField(full_name,"First name is required!")== false) {full_name.focus();return false;}

if (ValidateRequiredField(email_address,"Email must be filled out!")== false) {email_address.focus();return false;}

if (ValidateEmailAddress(email_address,"Email is not in Valid format!")== false) {email_address.focus();return false;}

if (ValidateRequiredField(website_name,"Website name is required!")== false) {website_name.focus();return false;}

if (ValidateWebAddress(website,"Website Address is not incorrect format!")== false) {agreement.focus();return false;}

if (ValidateRequiredField(mobile,"Mobile must be filled out!", "number")== false) {phone.focus();return false;}

if (ValidateCheckBox(sex,"sex is not checked!")== false) {sex.focus();return false;}

}
}
</script>

And in you body where you are using the form just add the onsubmit=”return ValidateCompleteForm(this)” words in Form tag.

Exmaple:

<form action="submit.php" onsubmit="return ValidateCompleteForm(this)" method="post" >

Pure Javascript form Validation Script
Pure Javascript form Validation Script

Note: you can change the parameter as per your form fields names. Maxlength I kept 255 you can change this value as per your requirment.

Still if you have any doubts about this function please ask me.

add event to all image elements using javascript

In this article we will show to attach event to DOM element and add event to all image elements using javascript. Using javascript we can attach the event to any dom element.

add event to all image elements using javascript

You many times heard about getElementsByTagName javascript method but you did not tried.

getElementsByTagName function is very useful when you are working with javascript events. Using this function you can attach the event to any tag which is present in HTML body.

Here I am going to give the image example. Following script will attach the mouseover event to all images which are present in DOM.


var all_images = document.getElementsByTagName('img');

for (var i = 0; i < all_images.length; i++) {

addEvent(all_images[i], 'mouseover', myfunction, false);

}

function myfunction () {

 alert('this is image mouse over alert');

}

/**
 * cross-browser event handling for IE5+, NS6 and Mozilla
 * By Scott Andrew
 */
//This addEvent function we are using for external class use
this.addEvent = function(elm, evType, fn, useCapture) {
 if (elm.addEventListener) { // Mozilla, Netscape, Firefox
 elm.addEventListener(evType, fn, useCapture);
 return true;
 } else if (elm.attachEvent) {  // IE5 +
 var r = elm.attachEvent('on' + evType, fn);
 return r;
 } else {
 elm['on' + evType] = fn;
 }
}

</script>
add event to all image elements using javascript
add event to all image elements using javascript

If you copy paste the following code in your document and If you mouseover on any image then alert with message will come.

This script will work in any browsers. (IE 6,7,8, FF3,2, Safari3,4)

JSONP for cross domain communication solution using with javascript and PHP

Last year in Feb I heard about JSONP and really liked the JSONP solutions. JSONP allows you to make an HTTP request outside your own domain
JSONP consume the Web Services from JavaScript code. Earlier I worked on so on AJAX but there is issue with working or communication issue with cross domain sites.

JSONP for cross domain communication solution using with javascript and PHP
JSONP for cross domain communication solution using with javascript and PHP

XMLHttpRequest is blocked from making external requests.

JSONP for cross domain communication solution using with javascript and PHP

JavaScript code to make a JSONP call will as follows:

[viral-lock message=”Solution code is Hidden! It’s Visible for Users who Liked/Shared This article on Facebook or Twitter or Google+. Like or Tweet this article to reveal the content.”]

function common_jsonpRequest(url, name, query) {

 if (url.indexOf("?") > -1)
 url += "&jsonp="
 else
 url += name + "&";
 if (query)
 url += encodeURIComponent(query) + "&";
 url += new Date().getTime().toString(); // prevent caching

 var JSONPscript = document.createElement("script");
 JSONPscript.id = 'wordpressapi_jsonpRequest';
 JSONPscript.setAttribute("src", url + "&CacheBuster=" + Math.random());
 JSONPscript.setAttribute("type","text/javascript");

 // write the jsonp script tag
 document.body.appendChild(JSONPscript);
 //script.text = "";

}

function returncall (data){
 alert(data);
// you can use data as a variable also.
}

[/viral-lock]

In same javascript you should write the returning function as above.

You can call JSONP this function as follows;

<a href="http://images.purabtech.in/JSONP-request.gif">
<img class="alignnone size-medium wp-image-1167" title="JSONP-request" src="http://images.purabtech.in/JSONP-request-300x125.gif" alt="" width="300" height="125" />
</a>
common_jsonpRequest(base_url+'getData.php?jsonp=mycallback&name=for_wordpressapi');

Notel: getData.php file will beahave like externaal javascript file so handle this file carefully.
getData.php sample file.

<?php
$data = "this is our dynamic data";
if($_REQUEST['name']=='for_wordpressapi'){

echo "returncall(".$data.")";

}

?>&nbsp;

This will return the “this is our dynamic data” as a alert.

How to append html code using javascript and php

append html code using javascript and php, In this example I am going to show you how to add the dynamic HTML code into Document using javascript and PHP.

How to append html code using javascript and php

<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->php

$random_id = 125845465; // PUTTING SOME RANDOM ID YOU CAN USE YOURSELF.

$DYNAMIC_HTML = '<div>
<b>Sponsored Links</b>

<div>
 12px;font-weight:bold;" href="http://www.ucoz.com/" rel="nofollow">Create a website for free - uCoz

Build a website quickly and easily
Customizable templates and graphics

</div>

<div>
 12px;font-weight:bold;" href="http://www.purabtech.in/files/domain_names/">$1.99 Domain Names

 With every new non-domain purchase thru <a href="http://www.purabtech.in/files/domain_names/" rel="nofollow">wordpressapi</a>, you get a domain name for only $1.99.
</div>

<div>
 12px;font-weight:bold;" href="http://www.purabtech.in/files/" rel="nofollow">FREE Hosting!

 With every domain you register with <a href="http://www.purabtech.in/files/" rel="nofollow">wordpressapi</a> you get FREE hosting.
</div>
</div>';

 $HTML = "var objHead = document.getElementsByTagName('head');
 var objCSS = objHead[0].appendChild(document.createElement('link'));
 objCSS.id = '.$random_id.';
 objCSS.rel = 'stylesheet';
 objCSS.href = 'http://YOURSITE/STYLE.css';
 objCSS.type = 'text/css';";

 $HTML .= '
 var WORDPRESAPI_html_'.$random_id.' = document.createElement("div");
 WORDPRESAPI_html_'.$random_id.'.id = "WORDPRESAPI_html_'.$random_id.'";
 WORDPRESAPI_html_'.$random_id.'.style.position = "absolute";
 WORDPRESAPI_html_'.$random_id.'.style.zIndex = "100";
 WORDPRESAPI_html_'.$random_id.'.style.left = "0px";
 WORDPRESAPI_html_'.$random_id.'.style.top = "0px";
 WORDPRESAPI_html_'.$random_id.'.style.visibility = "hidden";
 WORDPRESAPI_html_'.$random_id.'.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
 WORDPRESAPI_html_'.$random_id.'.innerHTML = "'.addcslashes($DYNAMIC_HTML,"\\\'\"&\n\r<>").'";
 document.body.appendChild(WORDPRESAPI_html_'.$random_id.');';

echo $HTML;

?>

In this code if you observe then following line is very important.

 WORDPRESAPI_html_'.$uniqid.'.innerHTML = "'.addcslashes($HTML,"\\\'\"&\n\r<>").'"; 
How to append html code using javascript and php
How to append html code using javascript and php

Whenever you are using javascript and PHP both together then use following way to push your HTML in Dom.

check html 5 is support in browsers through javascript

HTML5 is new version of HTML and many people does not aware of it.  In article, we checked html 5 is support in browsers through javascript. HTML5 is a new version of HTML and XHTML. The HTML5 draft specification defines a single language that can be written in HTML and XML.

check html 5 is support in browsers through javascript

It attempts to solve issues found in previous iterations of HTML and addresses the needs of Web Applications, an area previously not adequately covered by HTML.

check html 5 is support in browsers through javascript
check html 5 is support in browsers through javascript

In one of my project I need to use HTML5 methods and properties through javascript. So first I need to check or dectect with multiple browsers is there way to find HTML5 compability with browsers.I

Main introduced features are like canvas, video, or geolocation. Using that we can easily dectect the browsers compability.


if (navigator.geolocation) {
/* geolocation is available */
} else {
alert("I'm sorry, but geolocation services and HTML5 are not supported by your browser.");
}

or

if (window.postMessage) {
/* postMessage method is available */
} else {
alert("I'm sorry, but postMessage method and HTML5 are not supported by your browser.");
}

I am still searching for better solution…

How to check iframes are loaded completely in browser

Many times we use the iframes in site for loading the some extra content. Some time we need trigger events when iframes are loaded completely in browser. Here we check iframes loaded.

iframes are loaded completely in browser

In webpage loading Iframe and controlling site UI is very important.

This script is able to check local or cross domain iframe is loaded or not.

I tested following script with various browsers and OS. So there is no cross browser issue.

[viral-lock message=”Code is Hidden! It’s Visible for Users who Liked/Shared This article on Facebook or Twitter or Google+. Like or Tweet this article to reveal the content.”]


var iframe = document.createElement("iframe");
iframe.src = "https://purabtech.in/";
if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera){
iframe.onreadystatechange = function(){
if (iframe.readyState == "complete"){

alert("Iframe is now loaded.");
}
};
} else {
iframe.onload = function(){

alert("Iframe is now loaded.");
};
}


[/viral-lock]

 

iframes are loaded completely in browser
iframes are loaded completely in browser

Have fun!

How to javascript append html string to element

Javascript tutorial, Article for, How to javascript append html string to element. I created following script putting the html at end of body tag.

javascript append html string to element

If you are using or following web 2.0(Table less HTML) standards for creating the HTMLs then this script will work 100%

Just Put this script in your HTML and see the html source. You will able to see the div id named “kapil” with the test content.


<script type=’text/javascript’>
var kapil = document.createElement(‘div’);
kapil.id = ‘form_kapil’;
var all_divs = document.getElementsByTagName(‘div’);
if (document.body.firstChild){
document.body.insertBefore(kapil, all_divs[all_divs.length] );
} else {
document.body.appendChild(kapil);
}
var oldHTML = document.getElementById(‘form_kapil’).innerHTML;
var newHTML = “test content”;
//document.getElementById(‘form_kapil’).innerHTML = newHTML;
var all_divs = document.getElementsByTagName(“div”);
//alert(all_links[all_links.length - 1].innerHTML);
all_divs[all_divs.length - 1].innerHTML = newHTML;
</script>

Have fun!

Finding mouse position browser and screen size javascript

This article will be use for Finding mouse position browser with only javascript. Javascript is base for many framework. If you have strong knowledge of javascript then you will be able to write any code in web sites.

Following script Will tested and working on following browsers.
1. Firefox 2+
2. Google chrome
3. Safari
4. IE 6, 7, 8
5. Opera
You can Use following code for Capturing the Mouse coordinates as per Document body

var isIE = document.all?true:false;
// document.onmousemove = getMousePosition;
// document.onmousemove = getscreenPosition;
function getMousePositionBrowsersizeWise(e) { // as per Document body
var _x;
var _y;
if (!isIE) {
_x = e.pageX;
_y = e.pageY;
}
if (isIE) {
_x = event.clientX + document.body.scrollLeft;
_y = event.clientY + document.body.scrollTop;
}
alert(_x);
alert(_y);
}

You can Use following code for Capturing the Mouse coordinates as per Screen Resolution

function getMousePositionScreenWise() {
var ScrX = window.screenLeft != undefined ? window.screenLeft : window.screenX;
var ScrY = window.screenTop != undefined ? window.screenTop : window.screenY;
alert(ScrY);
alert(ScrX);
}

Following script Will tested and working on following browsers.1. Firefox 2+2. Google chrome 3. Safari4. IE 6, 7, 85. Opera
You can Use following code for Capturing the Mouse coordinates as per Document body

var isIE = document.all?true:false;// document.onmousemove = getMousePosition;// document.onmousemove = getscreenPosition; function getMousePositionBrowsersizeWise(e) { // as per Document body var _x; var _y; if (!isIE) { _x = e.pageX; _y = e.pageY; } if (isIE) { _x = event.clientX + document.body.scrollLeft; _y = event.clientY + document.body.scrollTop; } alert(_x);alert(_y); }

You can Use following code for Capturing the Mouse coordinates as per Screen Resolution

function getMousePositionScreenWise() {var ScrX = window.screenLeft != undefined ? window.screenLeft : window.screenX;var ScrY = window.screenTop != undefined ? window.screenTop : window.screenY;
alert(ScrY);alert(ScrX);
}

Following script Will tested and working on following browsers.1. Firefox 2+2. Google chrome3. Safari4. IE 6, 7, 85. Opera
You can Use following code for Capturing the Mouse coordinates as per Document body

var isIE = document.all?true:false;// document.onmousemove = getMousePosition;// document.onmousemove = getscreenPosition;function getMousePositionBrowsersizeWise(e) { // as per Document bodyvar _x;var _y;if (!isIE) {_x = e.pageX;_y = e.pageY;}if (isIE) {_x = event.clientX + document.body.scrollLeft;_y = event.clientY + document.body.scrollTop;}alert(_x);alert(_y);}

You can Use following code for Capturing the Mouse coordinates as per Screen Resolution

function getMousePositionScreenWise() {var ScrX = window.screenLeft != undefined ? window.screenLeft : window.screenX;var ScrY = window.screenTop != undefined ? window.screenTop : window.screenY;alert(ScrY);alert(ScrX);}

Following script Will tested and working on following browsers.1. Firefox 2+2. Google chrome 3. Safari4. IE 6, 7, 85. Opera
You can Use following code for Capturing the Mouse coordinates as per Document body

var isIE = document.all?true:false;// document.onmousemove = getMousePosition;// document.onmousemove = getscreenPosition;
function getMousePositionBrowsersizeWise(e) { // as per Document body  var _x;  var _y;  if (!isIE) {    _x = e.pageX;    _y = e.pageY;  }  if (isIE) {    _x = event.clientX + document.body.scrollLeft;    _y = event.clientY + document.body.scrollTop;  }
alert(_x);alert(_y);  }

You can Use following code for Capturing the Mouse coordinates as per Screen Resolution

function getMousePositionScreenWise() {var ScrX = window.screenLeft != undefined ? window.screenLeft : window.screenX;var ScrY = window.screenTop != undefined ? window.screenTop : window.screenY;
alert(ScrY);alert(ScrX);
}

limit of maximum length of url query string

Servers should be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations may not properly support these lengths.

limit of maximum length of url query string

The spec for URL length does not dictate a minimum or maximum URL length, but implementation varies by browser. On Windows: Opera supports ~4050 characters, IE 4.0+ supports exactly 2083 characters, Netscape 3 -> 4.78 support up to 8192 characters before causing errors on shut-down, and Netscape 6 supports ~2000 before causing errors on start-up.

Checking value from array javascript

Tutorial for Checking value from array javascript only. I found useful following URL working with Javascript Array.
http://www.javascriptkit.com/jsref/arrays.shtml

Here is my code to check value from array

var MyArrayVar = new Array(1, 2, 3, 4, 5);

testVar = 2;

if(MyArrayVar.indexOf(testVar) >= 0) {
alert("We got testVar in MyArrayVar");
}else{
alert("We did not got testVar in MyArrayVar");
}

As per this condition I am chekcing the What is returned by this MyArrayVar.indexOf(testVar).
You can check this by using “alert(MyArrayVar.indexOf(testVar));” line.
You will get this number value if testVar number or value present in Array.

You that value is not present in Array you will get the -1 result always.