Java Reference
In-Depth Information
Checking a passphrase for alphanumeric Characters
trY it out
You use what you've learned so far about regular expressions in a full example in which you check that
a passphrase contains only letters and numbers—that is, alphanumeric characters, not punctuation or
symbols like @ , % , and so on:
<!DOCTYPE html>
 
<html lang="en">
<head>
<title>Chapter 6, Example 2</title>
</head>
<body>
<script>
var input = prompt("Please enter a pass phrase.", "");
 
function isValid (text) {
var myRegExp = /[^a-z\d ]/i;
return !(myRegExp.test(text));
}
 
if (isValid(input)) {
alert("Your passphrase contains only valid characters");
} else {
alert("Your passphrase contains one or more invalid characters");
}
</script>
</body>
</html>
Save the page as ch6 _ example2.html , and then load it into your browser. Type just letters, numbers,
and spaces into the prompt box, click OK, and you'll be told that the phrase contains valid characters.
Try putting punctuation or special characters like @ , ^ , $ , and so on into the text box, and you'll be
informed that your passphrase is invalid.
Let's start by looking at the isValid() function. As its name implies, it checks the validity of the passphrase:
function isValid(text) {
var myRegExp = /[^a-z\d ]/i;
return !(myRegExp.test(text));
}
The function takes just one parameter: the text you want to validate. 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 first think about what pattern you are looking for.
What you want to find 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:
[^]
Search WWH ::




Custom Search