Tuesday, July 20, 2004

JavaScript Functions for Working with Cookies


// Cookie handeling routines.

// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function setCookie(name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
document.cookie = curCookie;
}

// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1)
end = dc.length;
return unescape(dc.substring(begin + prefix.length, end));
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie(name, path, domain) {
if (getCookie(name)) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"
function fixDate(date) {
var base = new Date(0);
var skew = base.getTime();
if (skew > 0)
date.setTime(date.getTime() - skew);
}

Monday, July 19, 2004

JavaScript Form Validation Functions (validate input)

Here's a link to a file contaning the functions posted in the last 10 or so posts, as well as some additional functions that can be extremely useful in form validation. Pay particular attention to the ValidateField() function toward the bottom of the JavaScript include file. It allows you to pass the field object (represented by 'this' in a JavaScript event), the type of validation you want to perform (i.e. "date", "email", "phone", "numeric", etc.), a flag indicating whether or not the field is required (i.e. can accept blanks) and a custom error message to display if the field fails validation. I've used it in many of my web projects and hope you will get some use out of it to.

You can download the JavaScript include file with the validation functions here:

http://www.related-pages.com/form_validation.js

JavaScript Function to Validate U.S. State (valid state)

This function tests the passed text against the U.S. State abbreviations, returning True if the text is a U.S. State abbreviation, False otherwise.


// Make sure a state is valid.
function ValidState(sstate) {
sstates = "wa|or|ca|ak|nv|id|ut|az|hi|mt|wy" +
"co|nm|nd|sd|ne|ks|ok|tx|mn|ia|mo" +
"ar|la|wi|il|ms|mi|in|ky|tn|al|fl" +
"ga|sc|nc|oh|wv|va|pa|ny|vt|me|nh" +
"ma|ri|ct|nj|de|md|dc";

if (sstates.indexOf(sstate.toLowerCase() + "|") > -1) {
return true;
}

return false;
}

JavaScript Function Allow Number keys Only (only digit)

This function returns True if the passed keycode is a digit, False if it is not. This is useful when you want to limit the values of a input field to only numbers.


function isDigit(nKeyCode)
{
// Test for digit keycode (0-9).
if((nKeyCode > 47) && (nKeyCode < 58))
{
return true;
}

return false;
}

JavaScript Function Validate Date (valid date)

This function returns True if the passed text is a valid date, False if it is not.


/*
ValidDate - true for valid date, false for invalid
*/
function IsValidDate(PossibleDate)
{
var PDate = new String(PossibleDate);

var regex = /(^\d{1,2})\/(\d{1,2})\/(\d{4,4})|(^\d{1,2})\/(\d{1,2})\/(\d{2,2})/;

if( regex.test(PDate) )
{
var month = new String(RegExp.$1);
var day = new String(RegExp.$2);
var year = new String(RegExp.$3);
if( month.length == 0 )
{
month = new String(RegExp.$4);
day = new String(RegExp.$5);
year = new String(RegExp.$6);
}

var today = new Date();
var thisYear = new String(today.getFullYear());

if( year.length == 2 )
{
if( year > 50 )
{
year = String(Number(thisYear.substring(0,2))-1) + year;
}
else
{
year = thisYear.substring(0,2) + year;
}
}

if( month < 1 || month > 12 ) { return false; }

if( day < 1 || day > 31 ) { return false; }

if ((month==4 || month==6 || month==9 || month==11) && day>30) { return false; }

if (month == 2) // check for february 29th
{
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap))
{
return false;
}
}

if( (Number(year) < Number(thisYear) - 250) ||
(Number(year) > Number(thisYear) + 250) )
{ return false; }

return true;
}
return false;
}

JavaScript Function to Validate SSN (valid ssn)

This function validates whether or not the passed text is a U.S. social security number, returning True if it is, False if it is not.


/*
ValidSSN - true for valid SSN, false for invalid
*/
function ValidSSN(SSN)
{
var SSNum = new String(SSN);

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

return regex.test(SSNum);
}

JavaScript Function to Validate Phone Number (valid phone number)

This function tests the passed text, returning True if the text is formatted in a valid U.S.A. phone number format, False otherwise.


/*
ValidPhoneNumber - true for valid phone number, false for invalid
*/
function ValidPhoneNumber(PhoneNumber)
{
var PNum = new String(PhoneNumber);

// 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}$/;

return regex.test(PNum);
}

JavaScript Function Is Numeric (validate number, valid number)

This function checks the passed text to see if it is a numeric value and returns True if it is, False if it is not.


/*
IsNumeric - true for all numeric, false if not
*/
function IsNumeric(PossibleNumber)
{
var PNum = new String(PossibleNumber);
var regex = /[^0-9]/;
return !regex.test(PNum);
}

JavaScript Function to Validate Email Addresses (valid email address)

This function validates an email address, returning True if it is a properly formatted email address, False if it is not.


/*
ValidEmail - true for valid email, false for invalid
*/
function ValidEmail(EmailAddr) {
var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;

var SpecChar="!#$%^&*()'+{}[]\|:;?/><,~`" + "\"";
var frmValue = new String(EmailAddr);
var len = frmValue.length;

if( len < 1 ) { return false; }
for (var i=0;i {
temp=frmValue.substring(i,i+1)
if (SpecChar.indexOf(temp)!=-1)
{
return false;
}
}

if(!reg1.test(frmValue) && reg2.test(frmValue))
{
return true;
}

return false;
}

JavaScript Function to Validate Zip codes (valid zipcode)

This function returns True if a Zipcode is a validly formatted U.S. Zip code, false if it is not.


/*
ValidZipCode - true for valid zip codes, false for invalid ones
*/
function ValidZipCode(ZipCode)
{
//Your zip code must contain 5 or 9 digits.
// 9 digit zip codes should contain no spaces and a
// hyphen before the last 4 digits.

var stringValue = new String(ZipCode);
var stringLength = stringValue.length;

if ((stringLength!=5)&&(stringLength!=9)&&(stringLength!=10))
{
return false;
}

if(stringLength==5)
{

for (var i = 0; i < stringLength; i++)
{
value = stringValue.charAt(i)
if (!((value >= 0) && (value <=9)))
{
return false;
}
}
}

if(stringLength==9)
{
for (var i = 0; i < stringLength; i++)
{
value = stringValue.charAt(i)
if (!((value >= 0) && (value <=9)))
{
return false;
}
}
}

if(stringLength==10)
{
var zip=stringValue.substring(0,5)
var symbol=stringValue.substring(5,6)
var plus4=stringValue.substring(6,10)

if(symbol!="-")
{
return false;

}


for (var i = 0; i < zip.length; i++)
{
value = zip.charAt(i)
if (!((value >= 0) && (value <=9)))
{
return false;
}
}
for (var i = 0; i < plus4.length; i++)
{
value = plus4.charAt(i)
if (!((value >= 0) && (value <=9)))
{
return false;
}
}

}
return true;
}

JavaScript Function to Trim White Space (RTRIM)

Like the LTRIM previously posted, this function trims white space, but from the right of the text.


/*
RTrim - Trims whitespace from right of a string
*/
function RTrim(str)
{
var whitespace = new String(" \t\n\r");

var s = new String(str);

if (whitespace.indexOf(s.charAt(s.length-1)) != -1)
{
var i = s.length - 1; // Get length of string
while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
i--;
s = s.substring(0, i+1);
}

return s;
}

JavaScript Function To Trim White Space (LTRIM)

This function trims the white space from the left of a string, a useful function when removing extra spaces typed in by a user into a form.


/*
LTrim - Trims whitespace from left of a string
*/
function LTrim(str)
{
var whitespace = new String(" \t\n\r");

var s = new String(str);

if (whitespace.indexOf(s.charAt(0)) != -1)
{
var j=0, i = s.length;
while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
{
j++;
}
s = s.substring(j, i);
}

return s;
}

JavaScript Function to Format Currency (Money)

I am going to be posting a series of useful JavaScript functions for form validation and input formatting. This is the first in that series: a function which formats a number as currency.


function formatCurrency(num)
{
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)) num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10) cents = "0" + cents;
return (((sign)?'':'-') + num + '.' + cents);
}