I'm going through some javascript and jQuery examples and some where i came across below code but i couldn't understand totally. I want to know what is the condition it is trying to validate.
function checkPostCode(toCheck)
{
var alpha1 = "[abcdefghijklmnoprstuwyz]"; // Character 1
var alpha2 = "[abcdefghklmnopqrstuvwxy]"; // Character 2
var alpha3 = "[abcdefghjkpmnrstuvwxy]"; // Character 3
var alpha4 = "[abehmnprvwxy]"; // Character 4
var alpha5 = "[abdefghjlnpqrstuwxyz]"; // Character 5
var pcex开发者_JAVA技巧p = new Array ();
pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "{1}" + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
pcexp.push (/^(GIR)(\s*)(0AA)$/i);
pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);
var postCode = toCheck;
var valid = false;
for ( var i=0; i<pcexp.length; i++) {
if (pcexp[i].test(postCode)) {
pcexp[i].exec(postCode);
postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
postCode = postCode.replace (/C\/O\s*/,"c/o ");
valid = true;
break;
}
}
if (valid) {return postCode;} else return false;
}
In general, this is referred to as "client side validation".
There are several regular expressions that are being added to the array pcexp
. The for()
loop checks each regular expression in the array, one at a time, to see if postCode
matches the pattern.
"If postCode
matches the current regular expression" is what the if()
statement inside the loop is saying.
The if()
statement at the end checks whether postCode
was matched against a pattern in the loop, thereby causing valid
to be set to true.
精彩评论