Java Reference
In-Depth Information
Let's start by looking at the regExpIs_valid() function defi ned at the top of the script block in the
head of the page. That does the validity checking of the passphrase using regular expressions.
function regExpIs_valid(text)
{
var myRegExp = /[^a-z\d ]/i;
return !(myRegExp.test(text));
}
The function takes just one parameter: the text you want to check for validity. You then declare a variable,
myRegExp , and set it to a new regular expression, which implicitly creates a new RegExp object.
The regular expression itself is fairly simple, but fi rst think about what pattern you are looking for. What
you want to fi nd out is whether your passphrase string contains any characters that are not letters between
A and Z or between a and z, numbers between 0 and 9, or spaces. Let's see how this translates into a
regular expression:
1.
You use square brackets with the ^ symbol.
[^]
This means you want to match any character that is not one of the characters specifi ed inside the
square brackets.
2.
You add a-z, which specifi es any character in the range a through z.
[^a-z]
So far, your regular expression matches any character that is not between a and z. Note that,
because you added the i to the end of the expression defi nition, you've made the pattern case-
insensitive. So your regular expression actually matches any character not between A and Z or
a and z.
3.
Add \d to indicate any digit character, or any character between 0 and 9.
[^a-z\d]
4.
Your expression matches any character that is not between a and z, A and Z, or 0 and 9. You
decide that a space is valid, so you add that inside the square brackets.
[^a-z\d ]
Putting this all together, you have a regular expression that will match any character that is not
a letter, a digit, or a space.
5.
On the second and fi nal line of the function, you use the RegExp object's test() method to
return a value.
return !(myRegExp.test(text));
The test() method of the RegExp object checks the string passed as its parameter to see if the char-
acters specifi ed by the regular expression syntax match anything inside the string. If they do, true
is returned; if not, false is returned. Your regular expression will match the fi rst invalid character
found, so if you get a result of true, you have an invalid passphrase. However, it's a bit illogical for an
is_valid function to return true when it's invalid, so you reverse the result returned by adding the
NOT operator (!).
Search WWH ::




Custom Search