Showing posts with label RegExp. Show all posts
Showing posts with label RegExp. Show all posts

Sunday, October 21, 2007

Javascript - trim() method...

Javascript is very cool in the way that i handles objects. The way that it lets you dynamically extend objects with properties and methodes, I find very cool.

Yes you need to keep focus due to this "anercistic" structure of javascript - sometimes you hate it but most of the times you probertly love it :-)

Anyway, I found a good example of this object extending feature. A trim method is not included in the standard javascript String object. So here you are - a way to extend String with a Regular Expression based trim() method:

String.prototype.trim = function() {
return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
}

(I found it here: Codeproject)

/Sten

Monday, January 22, 2007

RegExp validation of zip codes

Sometimes when sites are multi language you need some Javascript to validate ZIP codes for several countries. Here are some regular expression objects which you chan use:

var oRegExp_NoValidation = /.*/ig;
var oRegExp_DDDD = /^\d{4}$/ig;
var oRegExp_DDDDD = /^\d{5}$/ig;
var oRegExp_DDDDDD = /^\d{6}$/ig;
var oRegExp_Uk = /[A-Z][A-Z]?[0-9][A-Z0-9]? ?[0-9][ABDEFGHJLNPQRSTUWXYZ]{2}/ig
var oRegExp_DDDD_AA = /^\d{4}.[A-Z]{2}$/ig;
var oRegExp_DDDD_DDD = /^\d{4}-\d{3}$/ig;


I then create an object for the countries which I need to validate ZIP code for:

// countryCode:[regExpToUse, bLooseValidation]
// bLooseValidation => "not sure if postcode should confirm 100% to validator" :-(
var countryCodeRegExpRelation = {
dk:[oRegExp_DDDD, false],
be:[oRegExp_DDDD, false],
uk:[oRegExp_Uk, true],
fr:[oRegExp_DDDDD, false],
nl:[oRegExp_DDDD_AA, false],
it:[oRegExp_DDDDD, false],
lu:[oRegExp_DDDD, false],
po:[oRegExp_DDDD_DDD, false],
ch:[oRegExp_DDDD, false],
es:[oRegExp_DDDDD, false],
de:[oRegExp_DDDDD, false],
at:[oRegExp_DDDD, false],
cn:[oRegExp_DDDDDD, true],
us:[oRegExp_NoValidation, true],
UNKNOWN:[oRegExp_NoValidation, true]
}


Each country becomes a property of the object "countryCodeRegExpRelation", and it also has a definition stateing if it should be "strict". To get the RegExp for a ZIP code in say Polen, you should use the RexExp in the property: "countryCodeRegExpRelation.po[0]".

You might use this code to validateZIPCode:

function validateZIPCode(sCountryPrefix, sZIPCode) {
var oRegExp = countryCodeRegExpRelation[sCountryPrefix][0];
if (sZIPCode.match(oRegExp)!=null) {
return true
} else {
alert('ZIP code not valid!');
return false;
}