July 12th, 2007

How Can I Ensure That a User Enters Only Allowed Characters in a Text Box?

Hey, Scripting Guy! Question

Hey, Scripting Guy! I have an HTA which includes a text box where the user must enter a part number. Part numbers must consist of a certain set of characters; how can I determine if a user entered an invalid character in the part number text box?

— RR

SpacerHey, Scripting Guy! AnswerScript Center

Hey, RR. You know, with one exception, no one has ever accused the Scripting Guy who writes this column of being a genius. (The one exception, of course, is the Scripting Editor; she thinks that everything that this Scripting Guy does is just plain perfect.)

Editor’s Note: The Scripting Guy who writes this column is obviously having one of his delusional episodes. Don’t worry, it’s not serious; they’re mostly harmless and the Scripting Editor always manages to set him straight.

Still, the Scripting Editor aside, the Scripting Guy who writes this column will occasionally do something dumb. For example, it’s time for yet another out-of-town baseball tournament, this one to be held in beautiful Walla Walla, WA (“The town so nice they named it twice!”). Because of that, the Scripting Guy who writes this column is in a hurry to get today’s column taken care of; that way he can hit the road as quickly as possible. That means that the smart thing for him to do would be to pick a question – and write a column about – a topic he already knows by heart, one that he can sit down and hammer out a script and accompanying article without even thinking about it.

OK, not that he ever thinks too terribly hard about any column he writes. But you know what we mean.

Instead, the Scripting Guy who writes this column picked a question that he knew could be solved, although he wasn’t exactly sure how to go about solving it. Fortunately, with a little diligence and a little effort, along with the fact that he really needs to get going pretty soon, he was able to come up with the following solution:

<SCRIPT LANGUAGE=”VBScript”>
    Sub VerifyEntry
        Set objRegEx = CreateObject(“VBScript.RegExp”)
        objRegEx.Global = True   
        objRegEx.Pattern = “[^ABCDEFG12345]”

strSearchString = TextBox1.Value

Set colMatches = objRegEx.Execute(strSearchString)

If colMatches.Count > 0 Then Msgbox “You entered an invalid character.” TextBox1.Focus End If End Sub </SCRIPT>

<body> <input type=”text” name=”TextBox1″ size=”50″ onFocusOut=”VerifyEntry”><p> <input type=”text” name=”TextBox2″ size=”50″> </body>

We have a few minutes before we have to go, so let’s see if we can explain how this all works. To begin with, the body of our HTA consists solely of a pair of text boxes, text boxes that look identical, but actually have two key differences:

The names of the text boxes. The first text box (the one we care about) is named TextBox1. The second text box has an even catchier name: TextBox2. And, yes, now that you mention it, these two text boxes were named after the Scripting Guy’s mom and dad. Seemed like a nice anniversary present, don’t you think?

The events attached to each text box. Textbox2 doesn’t have any events attached to it; Textbox1, on the other hand, features the onFocusOut event. When you work with a control in an HTA or a Web page (for example, when you type something in a text box) that control is said to have the “focus.” When you leave that control (for example, by clicking somewhere else or by pressing the TAB key) the control loses the focus. When the control loses focus, the onFocusOut event fires, and – in this case—results in our HTA running the subroutine VerifyEntry.

Note. If none of that makes any sense to you that’s either because the Scripting Guy who writes this column repeated each and every word (“The column so nice he wrote it twice!”) or, more likely, because you aren’t familiar with HTAs. How can you become familiar with HTAs? Why, by checking out the HTA Developers Center, of course.

As you might expect, any excitement generated by this script will be generated by the VerifyEntry subroutine. In fact, the first thing we do inside this subroutine is very exciting: we create an instance of the VBScript.RegExp object. This, by the way, is a VBScript object that enables us to perform regular expression searches.

Note. What’s that? You’re not familiar with regular expression searches, either? Then you need to check out Dean Tsaltas’ now-classic webcast String Theory for System Administrators.

After creating the regular expression object we next set the Global property to True; that ensures that the script will search the entire value typed into TextBox1. (Technically we don’t need to search the entire value for this script. However, in most cases you will want to search the entire value; we added this line of code so you could see how to do that.) We then specify the Pattern we want to search for:

objRegEx.Pattern = “[^ABCDEFG12345]”

Regular expression syntax is always a bit goofy-looking (at best), so let’s explain what we’ve got here. We’re assuming that RR only allows the following characters to be entered as a part number:

A

B

C

D

E

F

G

1

2

3

4

5

By enclosing these characters in square braces we’re able to specify the set of characters that we’re looking for. Suppose we wanted to search for the characters X, Y, or Z? Then we’d use this syntax:

objRegEx.Pattern = “[XYZ]”

Of course, in this case, we don’t want to search for the characters in brackets; instead, we want to search for everything except the characters in brackets. Why? Well, suppose a user enters a part number of AB325@. We don’t need to search for the characters A, B, 3, 2, or 5; it’s perfectly legitimate for those characters to be included in the part number. Instead, we want to search for the @ sign, or for any other invalid character. That’s why our pattern includes the ^ mark in front of the character set; that’s regular expression syntax for, “Search for everything that isn’t included in the character set.” Want to search for X, Y, or Z? Then use this syntax:

objRegEx.Pattern = “[XYZ]”

Want to search for characters other than X, Y, or Z? Then use this syntax:

objRegEx.Pattern = “[^XYZ]”

Try the script a couple times and you’ll see how this works.

After defining the pattern we next need to identify the value we want to search. Because that value happens to be contained in the Value property of TextBox1 we use this line of code to assign the information typed into TextBox1 to a variable named strSearchString:

strSearchString = TextBox1.Value

From there we can call the Execute method and carry out our search:

Set colMatches = objRegEx.Execute(strSearchString)

As we noted a moment ago, what we’re doing here is searching the variable strSearchString for any character that is not part of the specified character set. For each such match (that is, for each character that isn’t part of the pattern) information about the match gets stored in the Matches collection (a collection we named colMatches). If all the characters in the string are valid characters then there won’t be any matches; in that case the value of the Count property will be 0. If an invalid character is found, that means that the collection will include at least one item. Our next step is to check for that very thing by using this line of code:

If colMatches.Count > 0 Then

If the Count is greater than 1 that means that we found at least one invalid character. In that case we execute these two lines of code:

Msgbox “You entered an invalid character.”
TextBox1.Focus

In the first line we simply echo back a message box stating that an invalid character was entered. In the second line, we then set the focus back to TextBox1. That essentially forces the user to enter a valid part number before he or she can continue with data entry.

That should do the trick. In the meantime, the Scripting Guy who writes this column is about to become the Scripting Guy who’s driving to Walla Walla. (Although that seems a little pointless, considering the fact that the Walla Walla Corn Maze doesn’t open until September 15th.) But don’t worry: although he’ll be out of town enjoying such attractions as the Nothing New antiques store (because new antiques are just never as much fun as old antiques) the Scripting Guy who writes this column will make sure that there’s a new Hey, Scripting Guy! each and every day. Does that means that he’s such a devoted and dedicated Microsoft employee that he’s willing to work on his vacation? You bet that’s what it means.

Well, that and the fact that he’s hoping to claim that these weren’t actually vacation days after all. Hey, he did write a new column each and every day, didn’t he? That sounds like work to us. (OK, true, it really isn’t much work. But it sounds like work.)

Author

0 comments

Discussion are closed.