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);
}

Tuesday, July 06, 2004

PHP Function For Adding Hours To A Date / Time

One of the things that I've always thought was a little lacking in PHP is its ability to easily perform date/time math.

In Visual Basic.NET there are functions called AddDays, AddHours, AddMinutes, etc. that make it very easy to adjust a date. In PHP there are no such functions. You have to go through a little more complexity to make this work.

Since I often needed a function to add hours to a date in my PHP applications, I wrote this little function to do it for me. Just pass in the date structure (returned by the getdate() function) that you want to add the hours to and the number of hours (positive or negative) that you want to add to the date.


// Returns the date adjusted by the number of hours specified.
function AddHours($date, $hours)
{
$newdate = date("m/d/y H:i:s", mktime($date["hours"] + $hours,
$date["minutes"],
$date["seconds"],
$date["mon"],
$date["mday"],
$date["year"]));
return $newdate;
}

Wednesday, June 23, 2004

Get the Compression Method of a TIFF in VB.NET (Visual Basic.NET)

This really bugged me. I found code all over the web for how to convert a TIFF from one compression format to another and how to convert a TIFF to every other kind of file format that .NET supports, but nowhere could I find a code snippet showing me how to know what compression method a TIFF is currently using except for a lone post on Google Groups.

So I am posting the code for knowing what the compression method of a TIFF is in VB.NET.



Private Function GetTiffCompressionType(ByVal FilePath As String) As Int32

Dim img As Bitmap
Dim c As Int32

Try
img = img.FromFile(FilePath)
c = Int32.Parse(img.GetPropertyItem(259).Value(0))
img.Dispose()
Catch ex As Exception
c = -1
End Try

'Return value:
'1 = ???
'2 = CCIT 3 (modified)
'3 = CCIT 3
'4 = CCIT 4
'5 = PackBits
'That's all I've discovered so far.
Return c

End Function

Wednesday, May 19, 2004

PHP Html Parser

A couple of days ago I posted some code for a VB.NET HTML Parser. If you need to do something similar using PHP, I've used this class with good success:

http://php-html.sourceforge.net/

It operates a little differently than the VB.NET parser, since it actually provides a means for you to walk down the document object model tree, but it works well.

Tuesday, May 18, 2004

Web Stats Tracking Script

Here's a groovy little script if you'd rather log your web stats to your own database than use a third party tracking script:


var asUrl = 'http://www.mysite.com/myscript.php?' +
'&url=' + escape(document.location.href) + '&pv=1' +
'&r=' + escape(document.referrer) +
'&dt=' + new Date().valueOf();
var bug = new Image();
bug.src = asUrl;


Paste that script onto your pages (or, preferably, put it into a javscript include file and use the SRC property of the SCRIPT tag to include it onto the page. It sends the URL of the page and the referrer to your script.

Here's a handy function that extracts the search keywords from the referrer if the referrer is a search engine. It captures all of the major search engines (Google, Yahoo, MSN, etc.) and most of the smaller ones. For your convenience I've included both the PHP and ASP.NET versions.

PHP Version

function getSearchKeywords($url)
{
$keywords = "";
$qvar = "";

if (strlen($url) == 0)
{
return "";
}

$url = trim($url);

$qloc = strpos($url, "?");
if (strpos($url, "/search/web"))
{
$keywords = substr($url, strpos($url, "/search/web/") + 12);
if (strpos($keywords, "/"))
{
$keywords = substr($keywords, 0, strpos($keywords, "/"));
}
$keywords = urldecode($keywords);
$keywords = str_replace(",", "", $keywords);
$keywords = str_replace(".", "", $keywords);
$keywords = str_replace("-", "", $keywords);
$keywords = str_replace("+", " ", $keywords);
$keywords = str_replace('"', "", $keywords);
return $keywords;
}
elseif (substr($url, 0, 24) == "http://search.yahoo.com/")
{
if (strpos($url, "&p=", $kloc + 1))
{
$kloc = strpos($url, "&p=", $kloc + 1);
}
if (!$kloc)
{
$kloc = strpos($url, "?p=");
}
$qvar = "p";
}
elseif (strpos($url, "&query=") | strpos($url, "?query="))
{
$kloc = strpos($url, "&query=");
if (strpos($url, "&query=", $kloc + 1))
{
$kloc = strpos($url, "$query=", $kloc + 1);
}
if (!$kloc)
{
$kloc = strpos($url, "?query=");
}
$qvar = "query";
}
elseif (strpos($url, "&searchfor=") | strpos($url, "?searchfor="))
{
$kloc = strpos($url, "&searchfor=");
if (strpos($url, "&searchfor=", $kloc + 1))
{
$kloc = strpos($url, "&searchfor=", $kloc + 1);
}
if (!$kloc)
{
$kloc = strpos($url, "?searchfor=");
}
$qvar = "searchfor";
}
else
{
$kloc = strpos($url, "&q=");
if (strpos($url, "&q=", $kloc + 1))
{
$kloc = strpos($url, "&q=", $kloc + 1);
}
if (!$kloc)
{
$kloc = strpos($url, "?q=");
}
$qvar = "q";
}

if (!$qloc | !$kloc)
{
return "";
}

$nextloc = strpos($url, "&", $kloc + 1);
if (!$nextloc)
{
$nextloc = strlen($url);
}

$keywords = substr($url, $kloc + strlen($qvar) + 2,
$nextloc - ($kloc + strlen($qvar) + 2));
$keywords = urldecode($keywords);
$keywords = str_replace(" ", " ", $keywords);
$keywords = str_replace(",", "", $keywords);
$keywords = str_replace(".", "", $keywords);
$keywords = str_replace("-", "", $keywords);
$keywords = str_replace("+", " ", $keywords);
$keywords = str_replace('"', "", $keywords);
$keywords = trim($keywords);

return $keywords;

}


ASP.NET Version

Public Function GetSearchKeywords(ByVal Url As String) As String

Dim keywords As String = ""
Dim kloc As Int32
Dim qloc As Int32
Dim nextloc As Int32
Dim qvar As String = ""

If Url Is Nothing Then
Return ""
End If

Url = Url.Trim()

qloc = Url.IndexOf("?")
If Url Like "*/search/web/*" Then
keywords = Url.Substring(Url.IndexOf("/search/web/") + 12)
If keywords.IndexOf("/") > -1 Then
keywords = keywords.Substring(0, keywords.IndexOf("/"))
End If
keywords = System.Web.HttpUtility.UrlDecode(keywords)
keywords = keywords.Replace(",", "")
keywords = keywords.Replace(".", "")
keywords = keywords.Replace("-", "")
keywords = keywords.Replace("+", " ")
keywords = keywords.Replace(Chr(34), "")
Return keywords
ElseIf Url.StartsWith("http://search.yahoo.com/") Then
kloc = Url.IndexOf("&p=")
If Url.IndexOf("&p=", kloc + 1) > -1 Then
kloc = Url.IndexOf("&p=", kloc + 1)
End If
If kloc = -1 Then
kloc = Url.IndexOf("?p=")
End If
qvar = "p"
ElseIf Url.IndexOf("&query=") > -1 Or _
Url.IndexOf("?query=") > -1 Then
kloc = Url.IndexOf("&query=")
If Url.IndexOf("&query=", kloc + 1) > -1 Then
kloc = Url.IndexOf("&query=", kloc + 1)
End If
If kloc = -1 Then
kloc = Url.IndexOf("?query=")
End If
qvar = "query"
ElseIf Url.IndexOf("&searchfor=") > -1 Or _
Url.IndexOf("?searchfor=") > -1 Then
kloc = Url.IndexOf("&searchfor=")
If Url.IndexOf("&searchfor=", kloc + 1) > -1 Then
kloc = Url.IndexOf("&searchfor=", kloc + 1)
End If
If kloc = -1 Then
kloc = Url.IndexOf("?searchfor=")
End If
qvar = "searchfor"
Else
kloc = Url.IndexOf("&q=")
If Url.IndexOf("&q=", kloc + 1) > -1 Then
kloc = Url.IndexOf("&q=", kloc + 1)
End If
If kloc = -1 Then
kloc = Url.IndexOf("?q=")
End If
qvar = "q"
End If

If qloc = -1 Or kloc = -1 Then
Return ""
End If

nextloc = Url.IndexOf("&", kloc + 1)
If nextloc = -1 Then
nextloc = Url.Length
End If

keywords = System.Web.HttpUtility.UrlDecode( _
Url.Substring(kloc + Len(qvar) + 2, _
nextloc - (kloc + Len(qvar) + 2))).Replace(" ", " ")
keywords = keywords.Replace(",", "")
keywords = keywords.Replace(".", "")
keywords = keywords.Replace("-", "")
keywords = keywords.Replace("+", " ")
keywords = keywords.Replace(Chr(34), "")
keywords = keywords.Trim

Return keywords

End Function

Monday, May 17, 2004

Web Based Remote SQL Server Administration

Here's a cool new free download from Microsoft. It allows you to (mostly) remotely administer your SQL Server installations over the web.

It lacks some of the more advanced management features like adding and running configured jobs and setting up detailed user security, but it's not too shabby for the price--free.

Click here to check it out.

Saturday, May 15, 2004

Visual Basic.NET Html Parser (VB.NET)

There have been numerous projects and tools that I've written in which I really needed the ability to extract a list of certain tags and their properties from an HTML document. For example, extracting all anchor (A) tags from a document and get their HREF property value.

When this became a need in a set of search engine optimization tools that I've written, I wrote a class that handles the parsing of an HTML document and the returning of an ArrayList of HtmlTag class objects. Here's an example of how it works:

Dim parser As New HtmlParser
Dim tags As New ArrayList
Dim tag As HtmlTag

tags = parser.GetTags(html, "A")

For Each tag in tags
MsgBox(tag.Properties("href"))
Next

The HtmlTag class requires some explanation:

Public Class HtmlTag
Public TagName As String = ""
Public Properties As New Hashtable
Public InnerHtml As String = ""
Public InnerText As String = ""
Public InnerTerms As String = ""
Public Sub New(ByVal TagName As String, _
ByVal Properties As Hashtable, _
ByVal InnerHtml As String, _
ByVal InnerText As String)
Me.TagName = TagName
Me.Properties = Properties
Me.InnerHtml = InnerHtml
Me.InnerText = InnerText
End Sub
Public Sub New()
End Sub
End Class

The TagName is set to the tag name (i.e. "A", "FONT", "H1", etc.).

The Properties property is a hashtable of all properties found in that tag (i.e. the "href" and "target" properties of an "A" tag). They're referenced easily with tag.Properties("[propertyname]") as shown in the example above.

The InnerHtml property contains all of the HTML code found between the opening and closing tags. So, for example, if I had a this tag in the HtmlTag object:

<a href="http://www.somesite.com">This is a<BR>link</a>

The InnerHtml property would contain This is a<BR>link

The InnerText property contains all of the text between the opening and closing tags with the HTML code stripped. So, using the example for InnerHtml, the InnerText property would contain This is a link.

The InnerTerms property may not be very useful to most people. It is a list of all of the "words" found in the InnerText property, separated by spaces. I used this when measuring keyword density in my search engine optimization tools.

The class code can be downloaded here. Just rename the file from ".txt" to ".vb" and add it to your project.

Free Chart and Graph Control for ASP.NET

I've used WebChart, a free ASP.NET charting and graphing control, in one of my ASP.NET projects. It works very well, outputs the images in PNG format, and even cleans up the storage directory by itself. Very nice.

It's not really full featured like some of the professional controls, but you can't beat the price tag. ;)

Check it out.