Archive for category Web

Bug tracking via Twitter?

An interesting thought just occurred to me… It seems quite reasonable to implement the Twitter API as a bug-tracking tool.

A software team could implement a Twitter account for bug tracking, and include the API into their projects within various try-catch blocks around potential points of failure. Then, all the members of that team would just follow that twitter account. For more critical applications, they could turn on device updates. It seems like a more available version of the elderly developer’s standby of programmatically emailing bug reports.

For sensitive applications, the tweets could be “protected”… but for less critical uses, the visibility of the public timeline would seem to be an added incentive for developers to fix bugs quickly.

It’s an interesting thought.

Tags:

Comments

String formatting for Javascript

Today, I was asked by a C# developer if Javascript has any string formatting functions comparable to the String.Format() method in C#.

I thought about it for a few minutes, going over the possibilities of regular expressions in my head, but finally settled on giving him a simple extension to Javascript’s String object.

String.prototype.format = function () {
	var str = this.toString();
	if (arguments.length == 0) return str;
	for (var i=0; i<arguments.length; i++) {
		str = str.replace('{'+i+'}', arguments[i]);
	}
	return str;
}

This simple function gives your Javascript strings the exact same formatting ability they would have in C#.

Test it out for yourself:

var s = 'Hello, {0}, I am {1}, and I am {2} to meet you.';
alert (s.format('foo','bar','baz'));

Tags:

Comments

CSS Blinker

The secret to user-friendly forms in web apps is to draw attention to errors before submitting the form, and to do so without accosting the user with irritating Javscript popups.

After filling in half a dozen (or more) form fields and then pressing the submit button, the user has mentally moved on. Suddenly hearing a “clunk” sound and getting a popup that says “invalid ssn” is jarring to say they least… but it also means the user must now read through all the form labels looking for something that sounds like “invalid ssn”.

My solution is to flash the form field drawing the user’s attention to exactly what information needs to be fixed. And for that, I have created Blinker.js.

Just include Blinker.js into your page. Then, during validation, when a field is not valid, just call Blinker:

1
Blinker.blink('element-id', 'error-classname');

Blinker uses the supplied CSS classname to do the blinking, so you can use any effect you want: change the text color, change the background, underline, add a border, whatever floats your boat. Just declare the desired style in your CSS and then use that class name in your call, along with the DOM ID of the element to flash.

The scrollTo option allows Blinker to scroll a field into the viewport if it’s not visible. The onDelay and offDelay allow you to customize the rate of blinking, and cycle determines the number of times to flash.

Tags: ,

Comments

Recursive script inclusion with REQUIRE (C#)

This is the C# version of the script I posted earlier. It’s also available as a VB.net version.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Collections;
using System.IO;
using System.Web;
 
public partial class javascript : System.Web.UI.Page
{
	private Stack files;
 
	protected void Page_Load(object sender, EventArgs e)
    {
		files = new Stack();
		Response.ContentType = "application/x-javascript";
		Response.Write(GetFile("js/Contacts.js"));
	}
 
	private string GetFile(string path)
	{
		string result = "";
		string filespec = HttpContext.Current.Request.PhysicalApplicationPath +
						 path.Replace("/", "\\");
 
		filespec = Path.GetFullPath(filespec);
 
		//if the file is already loaded, then exit
		if(files.Contains(filespec))
			return "";
 
		//add this file to the loaded list
		files.Push(filespec);
 
		//load the file
		string s = "";
		bool b = false;
		try {
			StreamReader sr = File.OpenText(filespec);
			do {
				b = true;
				s = sr.ReadLine() + "\n";
				if(s.IndexOf("//LIBRARY:") == 0)
					b = false;
 
				if(s.IndexOf("//REQUIRES:") == 0) {
					b = false;
					s = s.Replace("//REQUIRES:", "").Trim();
					result = result + GetFile(".." + s);
					s = "";
				}
				result = result + s;
			} while (sr.Peek() != -1 && !b);
			result = result + sr.ReadToEnd() + "\n";
			sr.Close();
		} catch {
			result = "\n/* Error loading file: " + filespec + " */\n"
		}
		return result;
    }
}

Tags: , ,

Comments

Recursive script inclusion with REQUIRE

One thing that tends to seriously limit the “best practices” when it comes to enterprise development and code reuse for Javascript is a lack of INCLUDE or REQUIRE functionality.

Code reuse and portability requires various functionality to be compartmentalized into individual .js files containing only related functionality, but on the web, including several files means making lots of unnecessary roundtrips, which can add up to a huge performance cost in the load time of your pages.

Good compartmentalized code also necessitates some sort of REQUIRE mechanism, which allows one unit of code (ie, script file) to specify when it won’t run properly without another unit of code.

Thus, while working on a VB.Net project, I created this simple Javascript loader, which looks at the name of the directory in which an app resides, and then looks for a javascript file by that name and loads it. Directives can be placed in that Javascript file (and in any subsequent file) requiring the inclusion of additional script files.

Not only does this allow for easier inclusion of libraries as needed, but it also makes it easier to strip out unused code if/when it is no longer needed by an app.

This source code is also available in a C# version.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Imports System.IO
 
Partial Class javascript
	Inherits System.Web.UI.Page
 
	Private files As Stack
 
	Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
		files = New Stack()
		Response.ContentType = "application/x-javascript"
		Response.Write(GetFile("js/Contacts.js"))
	End Sub
 
	Private Function GetFile(ByVal path As String) As String
		Dim result As String = ""
		Dim filespec As String = HttpContext.Current.Request.PhysicalApplicationPath & path.Replace("/", "\")
 
		filespec = IO.Path.GetFullPath(filespec)
 
		'if the file is already loaded, then exit
		If files.Contains(filespec) Then Return ""
 
		'add this file to the loaded list
		files.Push(filespec)
 
		'load the file
		Dim s As String = ""
		Dim b As Boolean = False
		Try
			Dim sr As StreamReader = File.OpenText(filespec)
			Do
				b = True
				s = sr.ReadLine() & vbCrLf
				If s.IndexOf("//LIBRARY:") = 0 Then
					b = False
				End If
				If s.IndexOf("//REQUIRES:") = 0 Then
					b = False
					s = s.Replace("//REQUIRES:", "").Trim()
					result = result & GetFile(".." & s)
					s = ""
				End If
				result = result & s
			Loop While sr.Peek() <> -1 And Not b
			result = result & sr.ReadToEnd() & vbCrLf
			sr.Close()
		Catch ex As Exception
			result = vbCrLf & "/* Error loading file: " & filespec & " */" & vbCrLf
		End Try
 
		Return result
	End Function
 
End Class

This could be easily updated to work for CSS files as well.

Tags: ,

Comments

Javascript XML extensions

While several features of Microsoft’s DOMDocument object are not supported by standards, it’s hard to deny that many of them are quite useful, and probably should be standardized.

When writing AJAX web apps, you need easy access to XML nodes. And more than anything, you need it to be cross-browser capable. To that end, I often include the following script in my AJAX apps.

/**
 * XML functions
 */
if (window.ActiveXObject) {
	/* Functions for IE */
	domLoadXml=function(xml){
		var doc=new ActiveXObject('MSXML2.DOMDocument');
		doc.async=false;
		doc.loadXML(xml);
		return doc;
	}
}else{
	/* Functions for non-IE browsers */
	domLoadXml=function(xml){
		var parser=new DOMParser();
		return parser.parseFromString(xml,'text/xml');
	}
	//fill in the missing convenience methods for Firefox
	Element.prototype.selectSingleNode=function(xpath){
		var xpe=new XPathEvaluator();
		var n=xpe.evaluate(xpath,this,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);
		if(n!=null) return n.singleNodeValue;
		else return null;
	}
	Element.prototype.selectNodes=function(xpath){
		var xpe=new XPathEvaluator();
		var xpr=xpe.evaluate(xpath,this,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE,null);
		var nodes=new Array();
		if(xpr!=null){
			var el=xpr.iterateNext();
			while(el){
				nodes.push(el);
				el=xpr.iterateNext();
			}
		}
		return nodes;
	}
	if(typeof HTMLElement.prototype.__defineGetter__ != 'undefined'){
		Element.prototype.__defineGetter__('xml', function() {return XMLSerializer().serializeToString(this);} );
		Element.prototype.__defineGetter__('text', function() {return this.textContent;} );
		Element.prototype.__defineSetter__('text', function(s) {this.textContent=s;} );
		//Element.prototype.__defineSetter__('xml', function(s) {} );
	}
}

Tags: ,

Comments

Javascript String functions

For any serious enterprise web apps, there are a handful of default Javascript functions I like to include in order to make my life easier in the long run.

Today, I present some handy extensions to the String object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
String.prototype.trim = function () {
	return this.replace(/(^\s+)|(\s+$)/, '');
}
String.prototype.addTrailingSlash = function () {
	return ('/' != this.charAt(this.length - 1)) ? this.toString() + '/' : this.toString();
}
String.prototype.left = function (n) {
	if (n <= 0) return "";
	else if (n > String(this).length) return this;
	else return String(this).substring(0,n);
}
String.prototype.right = function (n){
    if (n <= 0) return "";
    else if (n > String(this).length) return str;
    else {
       var iLen = String(this).length;
       return String(this).substring(iLen, iLen - n);
    }
}

The .trim() method is generally quite useful everywhere where text input is accepted.

The .addTrailingSlash() method is a nice way to help guarantee that you get valid paths and URLs when variables are involved.

The other two methods — .left() and .right() — are merely a conveniece at times, and I actually don’t find myself using them much as I prefer proper use of the .substring() method.

Tags:

Comments

Elegant date validation in Javascript

Why is date validation such a difficult concept for Javascript programmers? People are always trying way too hard to accomplish simple tasks. Let’s look at some of the wrong ways to do it.

This is from the top result on Google for “javascript valid date function”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Declaring valid date character, minimum year and maximum year
var dtCh = "/";
var minYear = 1900;
var maxYear = 2100;
 
function isInteger(s) {
	var i;
	for (i = 0; i < s.length; i++) {
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}
 
function stripCharsInBag (s, bag){
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}
 
function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
 
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
	}
	return this;
}
 
function isDate(dtStr) {
	var daysInMonth = DaysArray(12);
	var pos1 = dtStr.indexOf(dtCh);
	var pos2 = dtStr.indexOf(dtCh, pos1 + 1);
	var strMonth = dtStr.substring(0, pos1);
	var strDay = dtStr.substring(pos1 + 1, pos2);
	var strYear = dtStr.substring(pos2 + 1);
	strYr = strYear;
	if (strDay.charAt(0) == "0" && strDay.length > 1) strDay = strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length > 1) strMonth = strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length > 1) strYr = strYr.substring(1);
	}
	month = parseInt(strMonth);
	day = parseInt(strDay);
	year = parseInt(strYr);
	if (pos1 == -1 || pos2 == -1) {
		alert("The date format should be : mm/dd/yyyy");
		return false;
	}
	if (strMonth.length < 1 || month < 1 || month > 12) {
		alert("Please enter a valid month");
		return false;
	}
	if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]) {
		alert("Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || year == 0 || year < minYear || year > maxYear) {
		alert("Please enter a valid 4 digit year between " + minYear + " and " + maxYear);
		return false;
	}
	if (dtStr.indexOf(dtCh, pos2 + 1) != -1 || isInteger(stripCharsInBag(dtStr, dtCh)) == false) {
		alert("Please enter a valid date");
		return false;
	}
	return true;
}

Holy cow! That’s a large amount of code to include into a project, just for date validation. And worse, if you click through the links on the Google search, you’ll find countless examples of huge, over-complicated validation functions, occasionally mixed with smaller functions that are simpler, but inaccurate. Why is this so hard?

Let’s look at another one. This is actual code that was used by one of the companies I’ve worked for:

1
2
3
4
5
6
7
8
function validateDate(dateValue) {
	var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
	if ((dateValue.match(RegExPattern)) && dateValue.length >= 8 && dateValue.length <= 10) {
		return true;
	} else {
		return false;
	}
}

This regular expression seems to accurately validate dates, even for leap year, but it’s absolutely unmanageable. If any aspect of this validation is ever found to be lacking in some way, I pity the person who will have to fix it.

Why don’t people just use Javascript’s built-in Date object to validate their dates? JavaScript’s Date object is built to do some rather neat stuff. If you set the month or day to a value that is out of range, the Date object subtracts the difference and updates the entire date. For instance, if you set the month to April (which has 30 days), and then set the date to the 31st, the Date object will automatically change the month to May and the date to the 1st.

Thus, validating a date is rather easy. Here’s what I do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function validDate(date){
	//split the date using ANY separator
	var re = /(\d+)\D+(\d+)\D+(\d+)/;
	var a = date.match(re);
	if (a) {
		//check the year format
		if (a[3].length==2) a[3]= (a[3] > 69 ? '19' : '20') + a[3];
		if (a[3].length < 4) return false;
 
		//use integers and avoid octal parse errors for numbers starting with '0'
		a[1] = parseInt(a[1], 10);
		a[2] = parseInt(a[2], 10);
		a[3] = parseInt(a[3], 10);
 
		//use the Javascript Date object to validate the date
		var dt = new Date();
		dt.setFullYear(a[3]);
		dt.setMonth(a[1] - 1);
		dt.setDate(a[2]);
		if((a[1]==dt.getMonth() + 1) && a[2]==dt.getDate() && a[3]==dt.getFullYear())
			return (String(a[1]).length > 1 ? a[1] : '0' + a[1]) + '/' + (String(a[2]).length > 1 ? a[2] : '0' + a[2]) + '/' + a[3];
		else return null;
	}
	else return null;
}

There are a number of advantages to doing it this way. The first advantage is flexibility of formatting. This function accepts dates with ANY delimiter — you don’t have to check independently for dots, dashes, slashes, etc. It also gracefully handles 1-digit or 2-digit numbers for month and day, and 2-digit or 4-digit years.

The second advantage is that the hard work is done by JavaScript’s Date object, which is compiled and fast. All we’re doing here is setting the year, month, and day, and then checking to make sure it stayed where we set it. If it did, all the values were in their acceptable ranges.

And the third advantage to this function is that it returns a consistently formatted date for use throughout your code, or null if the input value is invalid.

So, if you want to validate and format a date in a text field, you can just add one line to the onblur handler:

1
<input type="text" name="datefield" value="" onblur="if (!(this.value=validDate(this.value))) alert('Please enter a valid date.');" />

Of course, I recommend using a more elegant event handler to do the validation, but if you’re lazy, it really is that simple.

So there you have it, a much better way to validate dates. Please note that this function assumes the date is in m/d/y format. Naturally, I have a way of handling different formats, as well, but I chose not to address that here since the functions I found for comparison don’t bother to address it.

Tags:

Comments

A quick link

I just stumbled onto this exhaustive index of resources, specifications, and tutorials for web design.

Comments

How iPhone affects web developers

A List Apart has just put up their second article about web sites developed for iPhone. In it, they discuss some of the limitations and difficulties of the device, such as:

There are also issues that arise because of the simplified user interface. After using the phone for awhile, you’ll notice that there are no open or save dialogs. Indeed, there is no file system that’s visible to the user, so it’s not surprising that the <input type=”file” …> does not work—there’s no way for a user to pick the file to upload.

The author describes everything from optimal screen size, font size, colors, memory limitations, downloads, fonts, and more.

Tags:

Comments