![]() |
Languages »
VB.NET »
Windows Forms
Intermediate
VB.NET Form Library: Password Character Validation and Log-In FormBy George B GilbertA form library with all the functionality you need to validate new passwords, and a prompt for a login password. |
VB, Windows, .NET, Visual Studio, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||

Demo project

Login form in the form library
This form library contains both a login form and a class you can use to validate whether or not new passwords have a correct character mix. The criteria used in the validation routine are, I think, acceptable in most systems. I took these requirements from the password validation routine in use at a local university for student access. Each password must be 6 to 10 characters long, and must contain at lease one number, one lower case letter, and one upper case letter.
I'm at the start of a large project to write several applications in a new product line. At least one, and possibly more, of the programs in this series will include password controlled access. This form library will make it easy to plug this functionality into new programs with very little effort.
A form library is a another name for a class library. The only difference is that a form library contains one or more forms while a class library does not. What this means is that when you start out to build a form library, don't look for that library type in the New Project list of templates. It isn't there.
Building a form library is not magical if you are aware of a couple of subtle reference requirements. In addition, you must provide some type of interface that allows the caller of your form to set up the form and receive values back. It is very much like adding a form to a Windows application. Here're the differences.
In Visual Studio, add a new project of type Visual Basic Projects with a Class Library template. For my library, I used the name 2gs_passwords.
In the new project, open the Solution Explorer and delete the default Class1.vb class. Now, expand the References section. You should see this list of references:

Before you can add a form to your library, you have to add two System namespaces to the project References.
System.Drawing and System.Windows.Forms DLLs.
Your list of references should now look like this:

Open the Project menu and click on Add Windows Form. If needed, click on the Windows Form template. Change the name of the form to something appropriate and click OK. I used F_Login.vb for my form name.
Before you start to flesh your form, make a subtle but necessary change to the automatically generated form code. Open the form's code view. It should look like this.

Add an Imports statement at the top of the code for System.Windows.Forms. Then, optionally shorten the Inherits statement to remove the namespace you moved to the Imports statement. When you are done, the code should look like this.

You can now construct your form just as you would in a Windows application. The login form in this library is a simple one with one label, one textbox, and two buttons.

The OK and Cancel buttons operate the way you would expect. The OK button checks if the user has entered the correct password. When the password is correct, a DialogResult of OK is returned and the form closed. When the password is not correct, a counter is incremented that keeps track of how many passwords the user has entered and the user is informed of their mistake. After the maximum number of allowed tries, a cancellation is returned and the form closed.
#Region " ... OK "
Private Sub btnOK_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnOK.Click
'-----------------------------------------------
' Date Developer Code Change
' ---------- ------------- --------------------
' 01/13/2006 G Gilbert Original code
'-----------------------------------------------
'-----------------------------------------------
' Check the password entered by the user
' against the current password
'-----------------------------------------------
If txtPassword.Text = _strCurrentPassword Then
'** The password checks
Me.DialogResult = DialogResult.OK
Me.Close()
Else
'** Keep track of how many times the
' user tries to enter the password.
_intTries += 1
'** After the maximum number of tries,
' change the message box title bar
If _intTries >= _intMaxTries Then
_strFormText = "Last Try"
End If
'** Tell the user the password is bogus
MessageBox.Show("Password is not correct", _
_strFormText, _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
txtPassword.Focus()
'** After the maximum number of tries,
' return a cancellation
If _intTries >= _intMaxTries Then
btnCancel.PerformClick()
End If
End If
End Sub
#End Region
#Region " ... Cancel "
Private Sub btnCancel_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnCancel.Click
'---------------------------------------------
' Date Developer Code Change
' ---------- -------------- -----------------
' 01/13/2006 G Gilbert Original code
'---------------------------------------------
Me.DialogResult = DialogResult.Cancel
Me.Close()
End Sub
#End Region
The OK click event code is pretty straightforward except for two questions ...
DialogResult is returned? The answer to both questions is in the form's interface (method). First, a storage location is needed for the current password so that when the interface receives it, the password can be placed in a location to which the OK click event has access. The private _strCurrentPassword string variable in the declaration section provides the needed storage location.
#Region " Members "
Private _strCurrentPassword As String
Private _strFormText As String = "Try Again"
Private _intMaxTries As Integer
Private _intTries As Integer
#End Region
The interface for this form is a public function that returns a boolean value. The parameters include the calling form object, the current password string, and an optional override for the maximum number of tries the user can enter a password.
#Region " ... LoginOK function "
Public Function LoginOK(ByVal ownerForm As Form, _
ByVal currentPassword As String, _
Optional ByVal numberOfTries _
As Integer = 3) As Boolean
'----------------------------------------------------------------
' Display the form
' Pass: ownerForm The calling form
' currentPassword The password the user must enter
' numberOfTries Optional maximum number
' of times the user is
' allowed to try to enter
' a correct password
' (defaults to 3)
' Return: True = user entered
' the correct password
' False = user cancelled or failed
' to enter the
' correct password
' in the allowed number
' of tries
'----------------------------------------------------------------
' Date Developer Code Change
' ---------- ------------ --------------------------------------
' 01/13/2006 G Gilbert Original code
'----------------------------------------------------------------
'----------------------------------------------------------------
' Make the current password available
' to the button events and set the maximum
' number of tries to enter that password
'----------------------------------------------------------------
_strCurrentPassword = currentPassword
_intMaxTries = numberOfTries
'----------------------------------------------------------------
' Display the login form and return
' the result of the user's attempts to log in
'----------------------------------------------------------------
Select Case Me.ShowDialog(ownerForm)
Case DialogResult.OK : Return True
Case Else : Return False
End Select
End Function
#End Region
The first task of the interface is to place both the current password and the maximum number of tries into the property variables to which the rest of the form's procedures have access. This answers the first question as to how the OK click event knows the current password.
Next, the interface displays the form as a dialog box with the calling form as the dialog owner. When either the OK or Cancel click events set a DialogResult, the interface receives the result and converts it to a true/false value that is returned to the calling form. This answers the second question as to how the calling application learns whether or not the user successfully entered the password.
The log-in form provides half of the functionality encapsulated in this form library. The other half, validating the character mix in a new password, is performed by the C_Password class. This class also has a method that is a public function which returns a boolean value. In addition to passing the password string being evaluated, the calling application can take advantage of a canned error message that is available for display when the password fails.
Imports System.Windows.Forms
Public Class C_Password
#Region " ... PasswordValid method "
Public Function PasswordValid(ByVal newPassword As String, _
Optional ByVal displayMsg As _
Boolean = True) As Boolean
'----------------------------------------------------------------
' Edit a password against the following
' criteria. Optionally display an error
' message if the password fails edit.
' > Must be 6 to 10 characters, and
' > Must contain at least 1 number,
' 1 lower case letter and 1 upper case letter
' Pass: newPassword The password being validated
' displayMsg True = If the password
' fails validation,
' display a canned
' message
' False = Do not display
' the canned message
' Return: True Password is valid
' False Password failed validation
'----------------------------------------------------------------
' Date Developer Code Change
' ---------- -------------------- ------------------------------
' 01/14/2006 G Gilbert Original Code
'----------------------------------------------------------------
'----------------------------------------------------------------
' Local Constant/Variable Declarations
'----------------------------------------------------------------
Dim i As Integer
Dim passwordOK As Boolean
Dim hasOneNumber As Boolean
Dim hasOneUCaseLetter As Boolean
Dim hasOneLCaseLetter As Boolean
'----------------------------------------------------------------
' Default to an invalid password
'----------------------------------------------------------------
passwordOK = False
'----------------------------------------------------------------
' Do the validation
'----------------------------------------------------------------
If newPassword.Length >= 6 _
And newPassword.Length <= 10 Then
hasOneNumber = False
hasOneUCaseLetter = False
hasOneLCaseLetter = False
For i = 0 To newPassword.Length - 1
Select Case Asc(newPassword.Substring(i, 1))
Case Asc("0") To Asc("9")
hasOneNumber = True
Case Asc("A") To Asc("Z")
hasOneUCaseLetter = True
Case Asc("a") To Asc("z")
hasOneLCaseLetter = True
End Select
Next
If hasOneNumber _
And hasOneUCaseLetter _
And hasOneLCaseLetter Then
passwordOK = True
End If
End If
'----------------------------------------------------------------
' If the password failed edit and an error message
' is requested, display same
'----------------------------------------------------------------
If Not passwordOK _
AndAlso displayMsg Then
Dim xMsg As String = _
"A password must be 6 to 10 characters long," _
& ControlChars.CrLf & _
"contain at least 1 number, 1 lower case letter," _
& ControlChars.CrLf & _
"and 1 upper case letter"
MessageBox.Show(xMsg, _
"Password Invalid", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
End If
'----------------------------------------------------------------
' Return the verdict
'----------------------------------------------------------------
Return passwordOK
End Function
#End Region
End Class
The only thing that I might point out about this very normal class is the Imports statement. Without the System.Windows.Forms namespace available, the MessageBox function is not declared.
To make the 2gs_passwords form library available in a project, follow these steps:
The demo project has the sample code for consuming both the form and the validation class in the library. Below are skeleton code snippets that focus on the structure needed to consume the class and the form. First, the validation class. In this snippet, the canned error message in the validation class is turned off by passing False as the second parameter to the PasswordValid method.
Dim passTest As New _2gs_passwords.C_Password
If passTest.PasswordValid(txtPassword.Text, False) Then
'
' Code executed when the password passes validation
'
Else
'
' Code executed when the password fails validation
'
End If
passTest = Nothing
Consuming the form is just as easy. In this skeleton code, the maximum number of tries the user can enter the password is changed from the default 3 to 5.
Dim loginForm As New _2gs_passwords.F_Login
Select Case loginForm.LoginOK(Me, txtPassword.Text, 5)
Case True
'
' Code executed when the user logs in successfully
'
Case Else
'
' Code executed when the user either cancels or
' fails to enter the password in the maximum
' number of tries
'
End Select
loginForm = Nothing
This form library does not address the issue of secure storage of the passwords. That is a topic way beyond the scope of this article. However, whichever method you employ to protect your library of passwords, this form library will handle the log-in function, and the validation of new passwords entered by users. Those two functions are common regardless of how the passwords are stored.
When is a form library appropriate? The answer to that question is the same as when is a class library appropriate? Build a form library whenever you create a form that can be re-used. Common examples of form libraries are the standard Open File and Print dialog boxes. If you, or anyone else, can re-use a form in two or more applications, put it in a form library (and hopefully publish it on The Code Project).
You may use all code offered in this article any way you choose without restriction.
Under no circumstances, and under no legal theory, tort, contract or otherwise, will George Gilbert (hereafter referred to as "software author") or his licensors, be liable to the user of the Double Text library and all code offered in this article (hereafter referred to collectively as "article code") for any damages, including any lost profits, lost data, or other indirect, special, incidental or consequential damages, arising out of the use or inability to use the article code, and data or information supplied, even if the software author, his licensors or authorized dealer have been advised of the possibility of such damages, or for any claim by any other party.
| You must Sign In to use this message board. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 25 Jan 2006 Editor: Smitha Vijayan |
Copyright 2006 by George B Gilbert Everything else Copyright © CodeProject, 1999-2009 Web22 | Advertise on the Code Project |