为了可维护性,这样的事情通常最好写成一系列测试而不是一个大测试。
var filter = function (username) {
var allDigits = /^[0-9]+$/g,
allHyphens = /^[-]+$/g, //doesn't need a character class, but I find it's more readable
multiHyphens = /[-]+/g,
startsWith = /^[A-Za-z0-9]{1}/,
endsWith = /[A-Za-z0-9]{1}$/
hasInvalidChars = /[^A-Za-z0-9-]/,
meetsReqs = false;
if (username.length >= 5 || username.length <= 25) { //ensure correct length
meetsReqs = !allDigits.test(username);
meetsReqs = meetsReqs && !allHyphens.test(username);
meetsReqs = meetsReqs && !multiHyphens.test(username);
meetsReqs = meetsReqs && !hasInvalidChars.test(username);
meetsReqs = meetsReqs && startsWith.test(username);
meetsReqs = meetsReqs && endsWith.test(username);
}
return meetsReqs;
};