Monday, November 24, 2008

Validate with regular expression

////////////////////////////////////////////////////////////////////////////////////////////
// function: checkCodes
// Validate the code, only accept A-F and 0-9
////////////////////////////////////////////////////////////////////////////////////////////
function checkCodes(sCode) {

var bValidCode = /^[a-fA-F0-9]+$/.test(sCode);
return bValidCode;

}

////////////////////////////////////////////////////////////////////////////////////////////
// function: getMatchCodes
// Applies the RegExp to the given string, and returns the match information.
////////////////////////////////////////////////////////////////////////////////////////////
function getMatchCodes (){

var match = /s(amp)le/i.exec("Sample text");
//match then contains ["Sample","amp"]

}

////////////////////////////////////////////////////////////////////////////////////////////
// function: getCodes
// Matches given string with the RegExp. With g flag returns an array containing the
// matches, without g flag returns just the first match or if no match is found returns null.
////////////////////////////////////////////////////////////////////////////////////////////
function checkCodes() {

var str = "Watch out for the rock!".match(/r?or?/g)

//str then contains ["o","or","ro"]

}

No comments: