Validating Strings and Unsigned Numbers

One of the frequently overlooked JavaScript development practices is to validate the parameters passed into functions. Todays articles will look at two ways to validate string and an unsigned number parameters.

Example 1: Safe String Operation

var str_trim = function(s) {
	( + s).remove(/^\s\s*/).remove(/\s\s*$/);

Anytime a string is expected as a parameter, the developer has two approaches for validation: using a type detection function/comparison or simply ensuring that the parameter is a string using the concatenation method shown in Example 1. In JavaScript, if a developer needs a string, they simply need to concatenate an empty string onto the parameter and any object will be converted into a string. So in this case, no matter what is passed into the str_trim function, the function will not throw any exceptions due to s not being a string and not having the remove. A verbose developer can use this technique anytime they are using a string method on a variable, although large strings can slow down performance.

Example 2: Unsigned Number

var number_random_int = function(n) {
	var seed = (0 < n) ? n : 100;
	return parseInt(Math.random() * seed);

In Example 2, the developer is expecting that parameter n is a positive number. The method number_random_int returns a random number between 0 and n, but requires that n be positive, otherwise, it will default to 100. Because JavaScript autocasts variables, any non-number object passed into the function will be determined as NaN (Not A Number) and ignored by the comparison, but any number (or number as a string) provided will validate (this can be a gotcha with this technique as you are not validating that n is a number, just that it evaluates as a positive integer; so dont use this technique, if you plan on concatenating n). The only other object that will also resolve to a number is the Date object, which will resolve to the getTime of the date.


In other news, I have the DomAutoPlay function working both forwards and backwards now. However, it required a massive overhaul of the version that I wrote last week and I plan to write about it this weekend.