Thursday, August 21, 2008

JS: Simple Regular expressions

Regex to validate Alpha-Numeric with whitespace:

var reg = /^[a-zA-Z0-9\s]+$/;
var val = document.getElementById("t1").value;
if(reg.test(val))
alert("Contains only Alphanumeric.");
else
alert("Contains other than alpha numeric.");

here "t1" is the Text control



Regex to trim the white spaces before and after a content:

function trim ( strToTrim )
{
return strToTrim.replace(/^\s+|\s+$/g,"");
}

var val = document.getElementById("t1").value;
alert("-"+trim(val)+"-");

No comments: