Java Reference
In-Depth Information
Previously you saw the two-line validity checker function using regular expressions. Just to show how
much more coding is required to do the same thing without regular expressions, here is a second func-
tion that does the same thing as regExpIs_valid() but without regular expressions.
function is_valid(text)
{
var isValid = true;
var validChars = “abcdefghijklmnopqrstuvwxyz1234567890 “;
var charIndex;
for (charIndex = 0; charIndex < text.length;charIndex++)
{
if ( validChars.indexOf(text.charAt(charIndex).toLowerCase()) < 0)
{
isValid = false;
break;
}
}
return isValid;
}
This is probably as small as the non-regular expression version can be, and yet it's still 15 lines long.
That's six times the amount of code for the regular expression version.
The principle of this function is similar to that of the regular expression version. You have a variable,
validChars, which contains all the characters you consider to be valid. You then use the charAt()
method in a for loop to get each character in the passphrase string and check whether it exists in your
validChars string. If it doesn't, you know you have an invalid character.
In this example, the non-regular expression version of the function is 15 lines, but with a more complex
problem you could fi nd it takes 20 or 30 lines to do the same thing a regular expression can do in
just a few.
Back to your actual code: The other function defi ned in the head of the page is butCheckValid_onclick().
As the name suggests, this is called when the butCheckValid button defi ned in the body of the page is
clicked.
This function calls your regExpis_valid() function in an if statement to check whether the pass-
phrase entered by the user in the txtPhrase text box is valid. If it is, an alert box is used to inform
the user.
function butCheckValid_onclick()
{
if (regExpIs_valid(document.form1.txtPhrase.value) == true)
{
alert(“Your passphrase contains valid characters”);
}
If it isn't, another alert box is used to let users know that their text was invalid.
else
{
alert(“Your passphrase contains one or more invalid characters”);
}
}
Search WWH ::




Custom Search