5,445,109 members and growing! (14,939 online)
Email Password   helpLost your password?
Languages » VB.NET » Windows Forms     Intermediate

VB.NET Form Library: Password Character Validation and Log-In Form

By George B Gilbert

A 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

Posted: 25 Jan 2006
Updated: 25 Jan 2006
Views: 58,754
Bookmarked: 38 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
7 votes for this Article.
Popularity: 2.85 Rating: 3.38 out of 5
1 vote, 14.3%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
4 votes, 57.1%
4
2 votes, 28.6%
5

Demo project

Login form in the form library

Contents

Introduction

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.

Background

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.

Building a Form Library

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.

1. Start Your Project With the Needed References

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.

  • In the Solution Explorer, right click on References to open the context menu.
  • Click on Add Reference.
  • On the .NET tab in the Add Reference window, select both the System.Drawing and System.Windows.Forms DLLs.
  • Once you have both of these DLLs listed under Selected Components, click the OK button.

Your list of references should now look like this:

2. Add A Form

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.

3. Provide An Interface

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 ...

  1. how does the form know the current password, and
  2. how does the calling application find out which 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.

Adding a Class to the Library

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.

Using the Form Library

To make the 2gs_passwords form library available in a project, follow these steps:

  1. Copy the DLL (2gs_passwords.dll) to the project's bin folder.
  2. In the Solution Explorer, add the DLL to the project's References.

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

Points of Interest

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.

Conclusion

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).


Licensing and Limitation of Liability

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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

George B Gilbert


Click here to see a complete list of my articles.
Occupation: Software Developer
Location: United States United States

Other popular VB.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralVB.net and Microsoft Access 2002memberspiral3:37 27 Aug '08  
GeneralRe: VB.net and Microsoft Access 2002memberGeorge B Gilbert4:48 27 Aug '08  
Questionauto loginmemberTeresa Madrid11:56 19 Oct '07  
AnswerRe: auto loginmemberGeorge B Gilbert13:35 19 Oct '07  
Generalchanging passwordmemberdida2622:14 9 Jul '06  
GeneralRe: changing passwordmemberGeorge B Gilbert6:43 10 Jul '06  
QuestionVC++7?memberHatemElbehairy3:52 25 Feb '06  
AnswerRe: VC++7?memberGeorge B Gilbert11:08 25 Feb '06  
GeneralRe: VC++7?memberGeorge B Gilbert14:00 25 Feb '06  
GeneralRe: VC++7?membercomputerguru923826:54 3 Mar '06  
GeneralRe: VC++7?memberGeorge B Gilbert7:37 3 Mar '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin 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-2008
Web19 | Advertise on the Code Project