Sunday, October 16, 2005

Some JavaScript functions I use

/* This function is used to validate that a string contains only [A-Za-z0-9.-_] which are the only valid characters in an email, (or perhaps a username). */

function valid(str) {
for(var i = 0; i < str.length; i++) {
var charcode = str.charCodeAt(i);

/* A-Z */
if(charcode >= 0x41 && charcode <= 0x5A) {
continue;
}

/* a-z */
if(charcode >= 0x61 && charcode <= 0x7A) {
continue;
}

/* 0-9 */
if(charcode >= 0x30 && charcode <= 0x39) {
continue;
}

/* . - _ */
if(charcode == 0x2D charcode == 0x2E charcode == 0x5F) {
continue;
}

return false;
}

return true;
}




/* This function is used to test that an e-mail address looks logical. This function uses the function valid() above. */

function testemail(email) {
var atpos = email.indexOf("@");

if(atpos == -1) {
return false;
}

if(atpos == 0) {
return false;
}

var dotpos = email.indexOf(".", atpos+2);

if( dotpos == -1) {
return false;
}

if(dotpos == (email.length - 1) ) {
return false;
}

var fpart = email.substring(0,atpos);
var host = email.substring(atpos + 1, dotpos);
var domain = email.substr(dotpos +1);

if(!( valid(fpart) && valid(host) &amp;& valid(domain))) {
return false;
}

var afterat = email.substr(atpos + 1);
if(afterat.lastIndexOf(".") == (afterat.length - 1)) {
return false;
}

for(var i = 1; i < afterat.length; i++) {
if(afterat.charAt(i) == "." && afterat.charAt(i-1) == ".") {
return false;
}
}

return true;
}


/* This function is used to trim a string (Removes the spaces before and after). */

function trim(str) {
var from_start = 0;
var from_end = str.length - 1;
var return_value;

while(str.charAt(from_start) == ' ') {
from_start ++;
}

while(str.charAt(from_end) == ' ') {
from_end --;
}

if(from_end < from_start) {
return '';
}
return_value = str.substring(from_start,from_end+1);
return return_value;
}



/* Hope that these functions would be useful to somebody out there as they where useful to me, hope you enjoy. */

No comments: