Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Wednesday, August 10, 2011

To Check Internet Explorer (IE) version


Little helper function to return details about IE 8 and its various compatibility settings either use as it is or incorporate into a browser object. Remember browser sniffing is not the best way to detect user-settings as spoofing is very common so use with caution.


function IEVersion(){
var _n=navigator,_w=window,_d=document;
var version="NA";
var na=_n.userAgent;
var ieDocMode="NA";
var ie8BrowserMode="NA";
// Look for msie and make sure its not opera in disguise
if(/msie/i.test(na) && (!_w.opera)){
// also check for spoofers by checking known IE objects
if(_w.attachEvent && _w.ActiveXObject){
// Get version displayed in UA although if its IE 8 running in 7 or compat mode it will appear as 7
version = (na.match( /.+ie\s([\d.]+)/i ) || [])[1];
// Its IE 8 pretending to be IE 7 or in compat mode
if(parseInt(version)==7){
// documentMode is only supported in IE 8 so we know if its here its really IE 8
if(_d.documentMode){
version = 8; //reset? change if you need to
// IE in Compat mode will mention Trident in the useragent
if(/trident\/\d/i.test(na)){
ie8BrowserMode = "Compat Mode";
// if it doesn't then its running in IE 7 mode
}else{
ie8BrowserMode = "IE 7 Mode";
}
}
}else if(parseInt(version)==8){
// IE 8 will always have documentMode available
if(_d.documentMode){ ie8BrowserMode = "IE 8 Mode";}
}
// If we are in IE 8 (any mode) or previous versions of IE we check for the documentMode or compatMode for pre 8 versions
ieDocMode = (_d.documentMode) ? _d.documentMode : (_d.compatMode && _d.compatMode=="CSS1Compat") ? 7 : 5;//default to quirks mode IE5
}
}

return {
"UserAgent" : na,
"Version" : version,
"BrowserMode" : ie8BrowserMode,
"DocMode": ieDocMode
}
}
var ieVersion = IEVersion();
var IsIE8 = ieVersion.Version != "NA" && ieVersion.Version >= 8;

if (!IsIE8) {
alert("Please upgrade to Internet Explorer 8 or better!" ) ;
}

Wednesday, July 13, 2011

Masking a HTML TextField as Numeric or Float

Add these functions to your JavaScript code under <script> tag.

function getKey(evt) { // works for IE, Netscape, Firefox, Opera, Chrome

var theEvent = evt || window.event;

var key = theEvent.keyCode || theEvent.which;

return key;

}

function MaskNumeric(evt) {

//8 Delete, 39 left cursor, 37 right cursor, 35 end, 36 home, 9 tab, 116 f5

//127 Backspace 48-57 0-9

var key = getKey(evt);

if( (key == 116 || key == 8 || key == 9 || key == 39 || key == 37 || key == 35 ||

key == 36 || key == 189 || key == 109 || key == 127 || key == 46) ||

(key >= 48 && key <= 57) ||

(key >= 96 && key <= 105) ) {

return true;

} else {

return false;

}

}

function MaskFloat(evt) {

//8 Delete, 39 left cursor, 37 right cursor, 35 end, 36 home, 9 tab, 116 f5

//127 Backspace 48-57 0-9

var key = getKey(evt);

if( (key == 116 || key == 8 || key == 9 || key == 39 || key == 37 || key == 35 ||

key == 36 || key == 189 || key == 109 || key == 127 || key == 46 || key == 110 || key == 190) ||

(key >= 48 && key <= 57) ||

(key >= 96 && key <= 105) ) {

return true;

} else {

return false;

}

}


Then use the following code in your HTML form.

For Numeric Masked Field:

<input type="text" onkeypress="return MaskNumeric(event);" />

For Float Masked Field.

<input type="text" onkeypress="return MaskNumeric(event);" />


Monday, August 2, 2010

Javascript: Checkall/Uncheckall feature in the enclosing Form

on the web page dynamically generated, I am having different number fo forms and in each form I have a list of checkboxes genererated dynamically.
The number of textboxes in a form may varry, but in each form the checkbox Id/name will have a certain prefix to identify.
The following piece of Java Script code can be used to checkall/uncheckall the checkboxes in a specific form on some event(button, checkbox or any other javascript event)

Simply place the following piece of code in the head section of your web page:


/**
*Prototypes for JS functions
*/
String.prototype.startsWith = function(str){return (this.match("^"+str)==str)}
String.prototype.endsWith = function(str){return (this.match(str+"$")==str)}

/**
*START SEGMENT:
*Check/Uncheck all the checkboxes in the selector column of a report.
*/
function getArray(formName,inputtype, prefix)
{

var checkBoxesArray=new Array();
var count = 0;
for(i=0; i < formName.elements.length ; i++)
{
var elmNameStr = formName.elements[i].name.toString();
var elmName =formName.elements[i];

//alert (elmName+ " :: elementName (startsWith): "+ elmNameStr.startsWith(prefix));

if(formName.elements[i].type==inputtype && elmNameStr.startsWith(prefix))
{
checkBoxesArray[count++] = elmName;
}
}
//alert(checkBoxesArray.length + " checkboxes found");
return checkBoxesArray;
}

function checkall(elem,flag,pattren)
{
var form = findParentForm(elem);

var arrayCheckboxes = getArray(form,"checkbox", pattren);

for ( i = 0 ; i < arrayCheckboxes.length ; i++) {
arrayCheckboxes[i].checked = flag;
}
}

function findParentForm(elem){
var parent = elem.parentNode;
if(parent && parent.tagName != 'FORM'){
parent = findParentForm(parent);
}
return parent;
}

/**
*END SEGMENT:
*/


To call the checkall functionality, simply call "checkall" function as:

onclick="javascript:checkall(this, this.checked,'butt-');"

@param1: Element Id you are calling on the function, usually a checkbox
@param2: Current state of check box, whether the checkbox state is checked or unchecked. If this checkbox is checked then all the associated checkboxes should also be checkd and vice versa
@param3: String prefix for the checkbox Id/name pattern to identify the appropriate list.

Example:



<form name ="formName0">

check/uncheck all: <input type ="checkbox" name ="test" onclick="javascript:checkall(this, this.checked,'butt-');"/> <br/>
<hr/>
Must Change State: <br/>
<input type ="checkbox" name ="butt-1234"/>
<input type ="checkbox" name ="butt-2141"/>
<input type ="checkbox" name ="butt-3_abh"/>
<input type ="checkbox" name ="butt-asgas"/>
<input type ="checkbox" name ="butt-0"/>
<hr/>
Must have ignored:<br/>
<input type ="checkbox" name ="abc"/>
<input type ="checkbox" name ="def"/>

</form>
<hr/>
<h3> Form 2 </h3>
<form name ="FormName1">
<span>
<div id ="asda" name ="divName">
check/uncheck all: <input type ="checkbox" name ="test" onclick="javascript:checkall(this, this.checked,'selected-');"/> <br/>
<hr/>
Must Change State: <br/>
<input type ="checkbox" name ="selected-1af"/>
<input type ="checkbox" name ="selected-wf2"/>
<input type ="checkbox" name ="selected-3_abh"/>
<input type ="checkbox" name ="selected-asgas"/>
<input type ="checkbox" name ="selected-0"/>
<hr/>
Must have ignored:<br/>
<input type ="checkbox" name ="selected_sabah"/>
<input type ="checkbox" name ="abnsd"/>

</div>
</span>
</form>

Thursday, July 29, 2010

Javascript: How to Find the enclosing/parent FORM Element

I was working on a project and came across a situation where we have more than one forms being generated dynamically in one page. And each form contains lots of input fields. To identify the enclosing/parent form element on some action of input tags, I used the following code:

Put these two javascript functions in script tag under head section of your page:


function findParentForm(elem){
var parent = elem.parentNode;
if(parent && parent.tagName != 'FORM'){
parent = findParentForm(parent);
}
return parent;
}

function getParentForm( elem )
{
var parentForm = findParentForm(elem);
if(parentForm){
alert("Form found: ID = " + parentForm.id + " & Name = " +parentForm.name);
}else{
alert("unable to locate parent Form");
}

}




Here is the example to call this code:


<body>
<h3> Form 1 </h3>
<form name ="formName1" id ="formId1">
<span>
<div>
<input type ="button" name ="button1" value="button1" onclick="javascript:getParentForm(this);"/> <br/>
</div>
</span>

</form>
<hr/>
<h3> Form 2 </h3>
<form name ="FormName2" id ="formId2">
<span>
<div id ="asda" name ="divName">
<input type ="button" name ="button1" value="button2" onclick="javascript:getParentForm(this);"/> <br/>
</div>
</span>
</form>
</body>


Wednesday, February 4, 2009

JavaScript: TRIM Function

Following function is very helpful to trim the leading as well as trailing spaces in a string. To make use of this function, first add the following code snip(declaration) in your JS library or in head section of HTML.

String.prototype.trim = function() {
a = this.replace(/^\s+/, '');
return a.replace(/\s+$/, '');
};



Then you may call this function like:

Example No:1

alert("Test Case 1:" + " StrinValue ".trim()+"sabah" )

Example No:2

< name="textfieldid" type="text" onchange="this.value=this.value.trim()">

Saturday, January 10, 2009

Javascript: Function To Check Whether TextField is ReadOnly

The following Javascript function can be used to check whether the given control is read only or not?

Sample 1:

function isReadOnly()
{

var m = document.getElementById("TextBox1").getAttribute("Readonly");
if (m==true)
{
alert('Read Only!');
return true;
}

else

{

alert('Not Read Only');

return false;

}


}

Sample 2:


function isReadOnly(controlID)
{

var m = document.getElementById(
controlID).getAttribute("Readonly");

if (m==true)
{
alert('Read Only!');

return true;

}

else

{

alert('Not Read Only');

return false;

}


}

Friday, January 9, 2009

JavaScript: Masking on Text Field

It is quite often that when we create HTML forms we need masking in fields and most of the times in text fields(Text Boxes) for some specific type of input like for DATE, PHONE NO, CURRENCY etc. Couple of server side technologies provide built in controls for most common masking but a few does not.

The following Javascript function provides you the facility to customize you text boxes with specific masking.

For Example, you may need masking for data input like : DD/MM/YYYY e.g 31/12/2008
Similarly sometimes you may want to provide masking like: 121-23-1231
and sometimes you may want to provide masking like: 12-42-1412

The following function is smart enough to handle all these requirements with a little change in the input parameter.

function mask(str,textbox,loc,delim){
var locs = loc.split(',');

for (var i = 0; i <= locs.length; i++){
for (var k = 0; k <= str.length; k++){
if (k == locs[i]){
if (str.substring(k, k+1) != delim){
str = str.substring(0,k) + delim + str.substring(k,str.length)
}
}
}
}
textbox.value = str
}

Where the parameters are for:
  1. str - the value of the current textbox control,
  2. textbox - the actual textbox object, (so that the value can be set)
  3. loc - a string of multiple locations to place the specified character,
  4. delim - the character (delimiter) that you want to use a separator.
Examples to Call this function:

Step 1:
First of all add this function in the head section.

Step 2:
You need to call this function on onKeyUp & onBlur events like:

To provide the output like(121-23-1231):

You need to call this javascript function like:
< name="Field1" value="" type="text" onkeyup="javascript:return mask(this.value,this,'3,6','-');" onblur="javascript:return mask(this.value,this,'3,6','-');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="11">



To provide the output like(21/12/2009):

You need to call this javascript function like:
< name="Field2" value="" type="text" onkeyup="javascript:return mask(this.value,this,'2,5','/');" onblur="javascript:return mask(this.value,this,'2,5','/');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="10">


To provide the output like(12,23,2312):

You need to call this javascript function like:
< name="Field3" value="" type="text" onkeyup="javascript:return mask(this.value,this,'2,5',',');" onblur="javascript:return mask(this.value,this,'2,5',',');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="10">

To provide the output like(12#32#1312):

You need to call this javascript function like:
< name="Field3" value="12#32#1312" type="text" onkeyup="javascript:return mask(this.value,this,'2,5','#');" onblur="javascript:return mask(this.value,this,'2,5','#');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="10">

You may change your mask symbol and the places accordingly using the provided parameters.

Thursday, January 8, 2009

Javascript: Function To Validate Date Format DD/MM/YYYY

Please use the following java script to validate the Date in the format(DD/MM/YYYY) wherever you needed in transcription screens:

Place this code in the head section of your HTML/JSP and pass the value(12/12/2008) to function named as validateDateDDMMYYY(‘12/12/2008’)


function validateDateDDMMYYY(DateOfBirth)
{

var Char1 = DateOfBirth.charAt(2);
var Char2 = DateOfBirth.charAt(5);
// alert(Char1); alert(Char2);

var flag =false;

if ( Char1 =='/' && Char2 == '/' )
{
// alert ('valid positions of non numeric characters.');
flag = true;
}
else
{
// alert('invalid position of non numeric symbols');
flag =false;
}

var day;
var month;
var year;

day = DateOfBirth.substring(0,2);
month = DateOfBirth.substring(3,5);
year = DateOfBirth.substring(6,10);

// alert(day); alert(month);alert(year);
if( validDay(day) && validMonth(month) && validYear(year) && (flag ==true) )
{
// alert(' Valid Date')
return true;
}
else
{
alert('Invalid Date Format: Please enter DD/MM/YYYY for Date of Birth!');
return false;
}

} // end func

function IsNumeric(sText)
{
var ValidChars = "0123456789.";
var IsNumber=true;
var Char;

for (i = 0; i < sText.length && IsNumber == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
}
}

return IsNumber;
} // end func


function validDay(day)
{
if ( IsNumeric(day) )
{
if( day >0 && day <32)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}

}// end func


function validMonth(month)
{
if ( IsNumeric(month) )
{
if( month >0 && month <13)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}// end func



function validYear(year)
{
var d = new Date();
var currentYear = d.getFullYear();

if( year.length!= 4) { return false; }

if ( IsNumeric(year) )
{
if( year >0 && year <=currentYear)
{
return true;
}
else
{
return false;
}

}
else
{
return false;
}

}// end func

Javascript: Function To Validate Date Format DD/MM/YYYY

unhidewhenused="false" name="Medium Grid 2 Accent 1">

Pleas



function validateDateDDMMYYY(DateOfBirth)
{

var Char1 = DateOfBirth.charAt(2);
var Char2 = DateOfBirth.charAt(5);
// alert(Char1); alert(Char2);

var flag =false;

if ( Char1 =='/' && Char2 == '/' )
{
// alert ('valid positions of non numeric characters.');
flag = true;
}
else
{
// alert('invalid position of non numeric symbols');
flag =false;
}

var day;
var month;
var year;

day = DateOfBirth.substring(0,2);
month = DateOfBirth.substring(3,5);
year = DateOfBirth.substring(6,10);

// alert(day); alert(month);alert(year);
if( validDay(day) && validMonth(month) && validYear(year) && (flag ==true) )
{
// alert(' Valid Date')
return true;
}
else
{
alert('Invalid Date Format: Please enter DD/MM/YYYY for Date of Birth!');
return false;
}

} // end func

function IsNumeric(sText)
{
var ValidChars = "0123456789.";
var IsNumber=true;
var Char;

for (i = 0; i < sText.length && IsNumber == true; i++) { Char = sText.charAt(i); if (ValidChars.indexOf(Char) == -1) { IsNumber = false; } } return IsNumber; } // end func function validDay(day) { if ( IsNumeric(day) ) { if( day >0 && day <32) { return true; } else { return false; } } else { return false; } }// end func function validMonth(month) { if ( IsNumeric(month) ) { if( month >0 && month <13) { return true; } else { return false; } } else { return false; } }// end func function validYear(year) { var d = new Date(); var currentYear = d.getFullYear(); if( year.length!= 4) { return false; } if ( IsNumeric(year) ) { if( year >0 && year <=currentYear)
{
return true;
}
else
{
return false;
}

}
else
{
return false;
}

}// end func


Thursday, November 20, 2008

Javascript: Making Initial Letter Capital for text box

Following script will work to make the initial letter in your text box automatically.

I have placed this in onKeyup event, you can use it according to your own requirements.

onkeyup=
"this.value=this.value.substring(0,1).toUpperCase()
+this.value.substring(1,this.value.length)"


Here is the example:

Thursday, November 13, 2008

JavaScript: Function To Check Whether provided string contains some wildcard character

The following function returns true if the string value contains the specific wild-card character.

Parameters:

1- fieldValue -- String

It is a string that needs to be checked whether it contains some special/wildcard characters

2- wildChar -- String/ Single Char

It is a character that you want to search whether it is present in the string passed as first parameter of this function.


function containsWildCard(fieldValue, wildChar)
{
// var fieldValue = window.document.getElementById("fieldID").value;
if (fieldValue.split(wildChar).length > 1)
{
alert ("WildCard!");
return false;
}
else
{
alert ("No - WildCard!");
return true;
}

}

Monday, November 3, 2008

Javascript: Function To Get Currrent Time

function getCurrentTime()
{
var d = new Date();

var hour=d.getHours();
var minute=d.getMinutes();
var second=d.getSeconds();

if(hour<10)
{
hour = '0'+hour;
}
if(minute<10)
{
minute= '0'+minute;
}

if(second<10)
{
second= '0'+second;
}

var time =hour+':'+minute+':'+second

return time;
}

Monday, September 1, 2008

JavaScript: Ways to Hit Server Side using JavaScript

There are three ways to hit the server side application using JavaScript that may be some servlet/JSP/CGI Script. Following are the ways:

  1. Use AJAX to hit the Server Side. You can get the details on this from following post: http://www.codeproject.com/KB/ajax/SimpleAJAX.aspx
  2. Second way is to submit the form data using the JavaScript. Following sample JavaScript function will perform the required task. Make sure you place this function in your HEAD tag of HTML in a script tag.



function goForward() {
// alert ("Go Forward ..... ");
frm=document.forms[0];
frm.method="GET"; // POST

frm.action="ServerSidePage.jsp";//Some servlet/Some CGI Script/URL
frm.submit();
}

3. You can use the "document.location.href", and you can specify the server side path of any servlet/JSP/ CGI Script/ Other URL.

Example No:1
The following code segment will display an button on your page and when u will click on it, it will open the Google page.

"< i n p u t name="myButt" value="Call Server Side" onclick="document.location.href='http://www.google.com'" type="button" >

This example will look like this:


Example No:2

In this example, we select the an item from the drop down list and it will go to the page that you have specified in the value of selected option.

Place the following method in your HEAD section of HTML:

function callURL()
{
document.location.href= document.formName.SelectListID.options[document.formName.SelectListID.selectedIndex].value
}


Andplace the following code in body section of your HTML:

"
< f o r m name="formName">
< s e l e c t name="SelectListID" onchange="callURL();"> < o p t i o n value="http://www.sabahmyrsh.blogspost.com" select e d="selected">select an item from List:< o p t i o n value="http://www.alislam.org">AlIslam

Friday, August 22, 2008

Javascript function similar to Sleep of JAVA

Here is a Javascript function that works similar to the Thread.sleep(milliseconds) method of JAVA.

The code of the JavaScript function is as under:

function pause(numberMillis)
{
var now = new Date();
var exitTime = now.getTime() + numberMillis;
while (true)
{
now = new Date();
if (now.getTime() > exitTime)
return;
}
}

You need to call this function like
pause(1000) ;
to wait a second!

Monday, August 18, 2008

JavaScript: Print Button on Your Web Page

It is fairly simple to add a PRINT Button on your web pages using JavaScript. The best practise to provide the facility of printing on web page is to provide a page that does not contain the banners/headers/footers/menus etc.
For this just create another web page containing only the data you actually need to print; For this make sure the background is not dark or does not contains the darked background image. etc

You can use simple JavaScript built in method window.print(). For example the following code segment will place a print link on your webpage using the img tag of HTML.

< i m g onclick="window.print();" src="/images/PrinterIcon.gif"
style="cursor:hand;" />

(Replace the text /images/PrinterIcon.gif with the location of an icon in your site.)

Tuesday, April 8, 2008

JAvaScript function to Count no Of Specific Fields( Like TextBoxes)

Sometimes, you create textboxes or othe form fields dynamically using some server side scripting language. Then you may need to count the number of fields using some JAvaScript. The following javascript function will return the no of specific fields of a form passed in parameters:

It has two parameters:
1- formName:- It is the attribute name of the form
2- inputtype:- Type of Field as a String argument.

For Example if you would like to count the number of textBoxes in the HTML form, the following call will work.

var noOfTextBoxes = countElement(formName,"text");

Similarly, to count no of buttons in HTML form, call the function like:

var noOfTextBoxes = countElement(formName,"button");


Here is the implementation of JavaScript function:

function countElement(formName,inputtype)
{
var count =0;
for(i=0; i < formName.elements.length ; i++ )
{
if(formName.elements[i].type==inputtype)
{
//
alert(formName.elements[i].value);
count=count+1;

}
}
return count;
}







View Sabah u Din Irfan's profile on LinkedIn

Friday, March 14, 2008

JAVAScript: Function To Validate UK ZipCodes

// Method that validates the Basic Business Rules for UK Zip codes.

function checkPostCode(pc) { //check postcode format is valid
var test = pc;
var size = test.length
test = test.toUpperCase(); //Change to uppercase
while (test.slice(0,1) == " ") { //Strip leading spaces
test = test.substr(1,size-1);size = test.length
}
while(test.slice(size-1,size) == " ") { //Strip trailing spaces
test = test.substr(0,size-1);size = test.length
}
if (size == 0) {
return "please enter a valid postcode";
}
//document.details.pcode.value = test; //write back to form field
if (size <> 8){ //Code length rule
//return "please enter a valid postcode";
return test + " is not a valid postcode - wrong length";
}
if (!(isNaN(test.charAt(0)))){ //leftmost character must be alpha character rule
//return "please enter a valid postcode";
return test + " is not a valid postcode - cannot start with a number";
}
if (isNaN(test.charAt(size-3))){ //first character of inward code must be numeric rule
// return "please enter a valid postcode";
return test + " is not a valid postcode - alpha character in wrong position";

}
if (!(isNaN(test.charAt(size-2)))){ //second character of inward code must be alpha rule
//return "please enter a valid postcode";
return test + " is not a valid postcode - number in wrong position";
}
if (!(isNaN(test.charAt(size-1)))){ //third character of inward code must be alpha rule
//return "please enter a valid postcode";
return test + " is not a valid postcode - number in wrong position";
}
if (!(test.charAt(size-4) == " ")){//space in position length-3 rule
//return "please enter a valid postcode";
return test + " is not a valid postcode - space in wrong position";

}
count1 = test.indexOf(" ");count2 = test.lastIndexOf(" ");
if (count1 != count2){//only one space rule
return "please enter a valid postcode";
return test + " is not a valid postcode - only one space allowed";
}
return "OK";
}

Wednesday, March 12, 2008

JAVAScript: StringTokenizer Function

String.prototype.tokenize = tokenize;

function tokenize()
{
var input = "";
var separator = " ";
var trim = "";
var ignoreEmptyTokens = true;

try {
String(this.toLowerCase());
}
catch(e) {
window.alert("Tokenizer Usage: string myTokens[] = myString.tokenize(string separator, string trim, boolean ignoreEmptyTokens);");
return;
}

if(typeof(this) != "undefined")
{
input = String(this);
}

if(typeof(tokenize.arguments[0]) != "undefined")
{
separator = String(tokenize.arguments[0]);
}

if(typeof(tokenize.arguments[1]) != "undefined")
{
trim = String(tokenize.arguments[1]);
}

if(typeof(tokenize.arguments[2]) != "undefined")
{
if(!tokenize.arguments[2])
ignoreEmptyTokens = false;
}

var array = input.split(separator);

if(trim)
for(var i=0; i
{
while(array[i].slice(0, trim.length) == trim)
array[i] = array[i].slice(trim.length);
while(array[i].slice(array[i].length-trim.length) == trim)
array[i] = array[i].slice(0, array[i].length-trim.length);
}

var token = new Array();
if(ignoreEmptyTokens)
{
for(var i=0; i
if(array[i] != "")
token.push(array[i]);
}
else
{
token = array;
}

return token;
}
/////////////////////////////////

Monday, October 29, 2007

JavaScript: Some Useful Functions

toUpperFirstChar:
Accepts an object of type "Text" and converts the first character of the string to upper case.
Parameters: Object
Returns: n/a

Here is the defination:

function toUpperFirstChar(obj)
{
LTrimObj(obj);
obj.value = obj.value.substr(0,1).toUpperCase()+obj.value.substr(1,obj.value.length-1);
}


checkDateValidity:-
This method checks if the fDt is less than tDt or not.
Parameters: FromDate, ToDate
Returns: Boolean

Here is the defination..


function checkDateValidity(fDT,tDT)
{
var fyear=fDT.charAt(7)+fDT.charAt(8)+fDT.charAt(9)+fDT.charAt(10);
var tyear=tDT.charAt(7)+tDT.charAt(8)+tDT.charAt(9)+tDT.charAt(10);

var fm=fDT.charAt(3)+fDT.charAt(4)+fDT.charAt(5);
var tm=tDT.charAt(3)+tDT.charAt(4)+tDT.charAt(5);
var fmonth=MonthReplace(fm);
var tmonth=MonthReplace(tm);

var fday=fDT.charAt(0)+fDT.charAt(1);
var tday=tDT.charAt(0)+tDT.charAt(1);

fDate = new Date(fyear,fmonth-1,fday);
tDate = new Date(tyear,tmonth-1,tday);

if(fDate > tDate)
{
alert("From date must not be greater than to date");
return false;
}
else
{
return true;
}
}


varifyPassword:-
varifies if the password is more than 6 char long and it contains atleast one digit and 4 distinct characters.

Here is the defination of the function:

function varifyPassword(pass)
{
pass=Trim(pass);
var validFlag = 1;
if(pass.length < 6)
{
validFlag = 0;
}
else
{
alphaList=new Array();
numList=new Array();
var flag=0;
for(var i=0; i< pass.length; i++)
{
var oneChar=pass.charAt(i)
if(isAlphabet(oneChar))
{
var charFlag=1;
for(var p=0; p {
if(oneChar==alphaList[p])
{
charFlag=0;
break;
}
}
if(charFlag)
{
alphaList[alphaList.length]=oneChar;
}
}
else if(oneChar>=0 && oneChar <=9)
{
var numFlag=1;
for(var p=0; p {
if(oneChar==numList[p])
{
numFlag=0;
break;
}
}
if(numFlag)
{
numList[numList.length]=oneChar;
}
}
else
{
validFlag = 0;
break;
}


if ((alphaList.length >= 1) && (numList.length>= 1) && ((alphaList.length + numList.length) >= 4))
{
flag = 1;
break;
}
}

if(flag)
{
return true;
}
else
{
validFlag = 0;
}
}

if (! validFlag)
{
alert("The password is not valid, or needs to be updated. Consult the help page for instructions about choosing a valid password.")
return false;
}
}

Friday, September 28, 2007

JavaScript@ Validation Functions

1- Empty Field Validation:- (To check whether a text field is empty or not)

function IsEmpty(aTextField) {
if ((aTextField.value.length==0)
(aTextField.value==null)) {
return true;
}
else { return false; }
}
////////////////////////////////////////////////

2- Numeric Validation:- (To check whether a text field contains Numeric Values)

function IsNumeric(sText)
{
var ValidChars = "0123456789.";
var IsNumber=true;
var Char;


for (i = 0; i < sText.length && IsNumber == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
}
}
return IsNumber;

}
////////////////////////////////////////////////

3- Aplphabet Validation:- (To check whether a text field contains Alphabetic Values)


function IsAlphabet(sText)
{
var ValidChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var IsAlpha=true;
var Char;


for (i = 0; i < sText.length && IsAlpha == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsAlpha= false;
}
}
return IsAlpha;

}
/////////////////////////////////////////////////////////////////////////

3- Email Address Validation:- (To check whether a text field contains valid email value)


function isValidEmail(str) {
return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);

}