Thursday 17 November 2011

Common Javascript for validation


// JavaScript Document


// get element by id
function getObject(val){
return document.getElementById(val);
}


function trim(b)
{
var i=0;
while(b.charAt(i)==" ")
{
i++;
}
b=b.substring(i,b.length);
len=b.length-1;
while(b.charAt(len)==" ")
{
len--;
}
b=b.substring(0,len+1);
return b;
}

function checkAtLeastOneBox(name) {

count = 0;
elements = document.getElementsByName(name);
len = elements.length;

for (var i = 0; i < len; i++) {
var e = elements[i];
if (e.checked) {
count=count+1;
}
}

if (count == 0){
return false;
}
else {
return true;
}
}


function isCharsInBag (s, bag)
  {
    var i;
    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) return false;
    }
    return true;
 }

//function to check valid zip code
function isZIP(s)
  {
    return isAlphaNumeric(s);
 }


function isValidUrlAddress(strUrl) {// not working
 
   var v = new RegExp();
    v.compile("[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    if (!v.test(strUrl)) {
        return false;
    }
return true;
}



function checkURL(value) {

var urlregex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
if(urlregex.test(value))
{
return(true);
}
return(false);
}

function isValidUrl(strUrl) {
   var v = new RegExp();
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    if (!v.test(strUrl)) {
        return false;
    }
return true;
}

function isValidUrl2(strUrl) {
   var v = new RegExp();
    v.compile("^[A-Za-z0-9-_:\/]+\\.[A-Za-z0-9-_%&\?\/.=]+\\.[A-Za-z]+$");
    if (!v.test(strUrl)) {
        return false;
    }
return true;
 }
function isChar(s){
s=trim(s);
return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ");
}


function isName(s){
s=trim(s);
return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ- ");
}
function isPassword(s)
{

s=trim(s);
return isCharsInBag (s, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_");
}

//function to check valid Telephone,. Fax no. etc
function isPhone(s)
  {

return isCharsInBag (s, "0123456789-+(). ");//simple test

var PNum = new String(s);

// 555-555-5555
// (555)555-5555
// (555) 555-5555
// 555-5555

    // NOTE: COMBINE THE FOLLOWING FOUR LINES ONTO ONE LINE.

var regex = /^[0-9]{3,3}\-[0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\) [0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\)[0-9]{3,3}\-[0-9]{4,4}$|^[0-9]{3,3}\-[0-9]{4,4}$/;

// var regex = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/; //(999) 999-9999 or (999)999-9999
if( regex.test(PNum))
return true;
else
return false;

  }

function isAlphaNumeric(s){
    return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- ");
}

function isUserName(s){
s=trim(s);
    return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.");
}

function isEmpty(s)
{
s=trim(s);
 return ((s == null) || (s.length == 0));
}

//function to check valid email id
function isEmail(s)
{

var regex = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i
var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return regex.test(s);

}


function isInteger (s)
   {
      var i;

      if (isEmpty(s))
      if (isInteger.arguments.length == 1) return 0;
      else return (isInteger.arguments[1] == true);

      for (i = 0; i < s.length; i++)
      {
         var c = s.charAt(i);

         if (!isDigit(c)) return false;
      }

      return true;
}

function isDigit (c)
{
  return ((c >= "0") && (c <= "9"))
}



  //set focus on el or global variable gl_el;
  function setFocus(el){
if(el != "undefined"){
document.getElementById(el).focus();
setAlertStyle(el);
// addEvent(document.getElementById(el),'onblur',function(){ alert('hello!'); })
}else if(typeof gl_el != "undefined"){
gl_el.focus();
}
return true;

  }
 

  function setAlertStyle(el){
document.getElementById(el).style.border = '2px solid';
document.getElementById(el).style.borderColor = '000';
  }
 
  function unsetAlertStyle(el){
document.getElementById(el).style.border = '2px solid';
document.getElementById(el).style.borderColor = '#f0f0f1';
  }

function SetAllCheckBoxes(FormName,FieldName)
{
var isChecked=document.getElementById('checkAll').checked;

if(isChecked==true){
var CheckValue='true';

}
else
{
var CheckValue='';
}

if(!FormName)
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];

if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;

if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
{
objCheckBoxes[i].checked = CheckValue;


}
}

function isAllcheckBoxSelected(formObj,checkBoxName){
var status = false;
var countCheckBoxes = 0;
var objCheckBoxes = formObj.elements[checkBoxName];
countCheckBoxes = objCheckBoxes.length;
if(countCheckBoxes!=0){
for(var i = 0; i <countCheckBoxes; i++){
if(objCheckBoxes[i].checked==true){
status = true;
}else{
status = false;
break;
}
}
}if(!countCheckBoxes) {
if(objCheckBoxes.checked==true){
status = true;
}else {
status = false;
}
}
return status;
}


function checkMasterCheckBox(checkBoxObj,formName,checkBoxName,masterCheckBoxName){
allCheckBoxCheckedStatus = false;
formObj = getObject(formName);
masterCheckBoxObj = getObject(masterCheckBoxName);
allCheckBoxCheckedStatus = isAllcheckBoxSelected(formObj,checkBoxName);
//alert(allCheckBoxCheckedStatus);
if(checkBoxObj.checked==true){
if(allCheckBoxCheckedStatus==true){
masterCheckBoxObj.checked = true;
}
}else{
masterCheckBoxObj.checked = false;
}

}


function showchkbox(){
$(document).ready(function(){
$('#chkTab').toggle('slow');
$('#downarrow').toggle('slow');
});
}

/**
 * shows a popup<br />
 * depends on jquery<br />
 * there should be empty div named winhidelayer on page.<br />
 * @param id of popup div
 */
function showPopup(id){
    var height = $(window).height();
    var winwidth = $(window).width();

try{

$('#winhidelayer').show();
 $('#winhidelayer').css({
'left' : 0,
'top' :0,
'height' : height,
'width' : winwidth

});
}catch(error){
}
$('#'+id).show();
var snpopup = $('#'+id);
    var width = $(document).width();

    snpopup.css({
        'left' : width/2 - (snpopup.width() / 2),
        'top' : height/2 - (snpopup.height() / 2),
        'z-index' : 1000000                      
    });
}

/**
 * hide a popup<br />
 * depends on jquery<br />
 * there should be empty div named winhidelayer on page.<br />
 * @param id of popup div
 */
function hidePopup(id){
try{
$('#winhidelayer').hide();
}catch(error){
}
$('#'+id).hide();
}

/*
function isleap(yr)
{
 //var yr=document.getElementById("year").value;
 if ((parseInt(yr)%4) == 0)
 {
  if (parseInt(yr)%100 == 0)
  {
    if (parseInt(yr)%400 != 0)
    {
    //alert("Not Leap");
    return false;
    }
    if (parseInt(yr)%400 == 0)
    {
   // alert("Leap");
    return true;
    }
  }
  if (parseInt(yr)%100 != 0)
  {
   // alert("Leap");
    return true;
  }
 }
 if ((parseInt(yr)%4) != 0)
 {
    //alert("Not Leap");
    return false;
 }
}
*/


function daysInMonth(iMonth,iYear)
{


var days=32 - new Date(iYear, iMonth, 32).getDate();

return days;

}


 /*function CompDate(adate,bdate,msg)
{
start = document.getElementById('day').value+'-'+document.getElementById('month').value+'-'+document.getElementById('year').value+'-'+document.getElementById('hour').value+'-'+document.getElementById('min').value;
end = document.getElementById('day2').value+'-'+document.getElementById('month2').value+'-'+document.getElementById('year2').value+'-'+document.getElementById('hour2').value+'-'+document.getElementById('min2').value;
//alert(start); alert(end);
a = start.split('-');
b = end.split('-');
var sDate = new Date(a[2],a[0]-1,a[1],a[3],a[4]);
var eDate = new Date(b[2],b[0]-1,b[1],b[3],b[4]);

if (sDate <= eDate)
{
alert('right');
return true;
}
else
{
   alert('wrong');
return false;
}
}




var startDate=new Date();
startDate.setFullYear(2010,0,14);
var endDate  =new Date();
endDate.setFullYear(2010,0,14);


if (startDate>endDate)
  {
  alert("Today is before 14th January 2010");
  }
else if(startDate<endDate)
  {
  alert("Today is after 14th January 2010");
  }
   else if(startDate=endDate){
   
alert('Equal');
 }
 */



function validateZipCode(elementValue){
      var zipCodePattern = /^\d{5}$|^\d{5}-\d{4}$/;
      return zipCodePattern.test(elementValue);
 }

function allValid(s){
s=trim(s);
return isCharsInBag (s, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz. ");
}

function priceValid(s){
s=trim(s);
return isCharsInBag (s, "0123456789. ");
}
function validateHtml(str){
 if(str.match(/([\<])([^\>]{1,})*([\>])/i)==null)
return false;
 else
return true;
}
function isFloatNumeric(s){
   return isCharsInBag (s, "0123456789. ");
}

No comments:

Post a Comment