Wednesday, November 28, 2007

Javascript Goodies

No comments:


I’ve recently had to deal with some very run of the mill client side validation, namely validation a comma separated list of email addresses – I was so pleased with my cobble together of bits of code I found on the net that I thought Id post it here for the next time! Also a handy bit of script to “trim” a string in javascript and adding the trim method to the String object… NICE!

String.prototype.trim = function() { return this.replace(/^\s+\s+$/g, ''); }

function CheckEmailAddresses()
{
var recipients = document.getElementById('recipients').getAttribute('innerText').split(',');
var emailRegEx = /^(("[\w-\s]+")([\w-]+(?:\.[\w-]+)*)("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)(@\[?((25[0-5]\.2[0-4][0-9]\.1[0-9]{2}\.[0-9]{1,2}\.))((25[0-5]2[0-4][0-9]1[0-9]{2}[0-9]{1,2})\.){2}(25[0-5]2[0-4][0-9]1[0-9]{2}[0-9]{1,2})\]?$)/i
for (var email in recipients)
{
if(emailRegEx.test(recipients[email].trim()))
{
alert('good');
} else {
alert('bad');
}
}
}

Thanx go to the following locations:
Trim function: http://www.nicknettleton.com/zine/javascript/trim-a-string-in-javascript
Email Regex: http://xyfer.blogspot.com/2005/01/javascript-regexp-email-validator.html

Read More