dcsimg
Results 1 to 3 of 3

Thread: Data annotation for window forms input validation

  1. #1

    Thread Starter
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,484

    Data annotation for window forms input validation

    A common practice for company or paid for applications is to register a user with a first and last name and password or user name and password some will have a confirm password. With the information a system will validate if the user exists or not along with self-validation of a password.

    The process in this example is dependent on using data annotations so that a validate method can be called against a class instance populated by values (in this case) entered in TextBox controls.

    Source code on GitHub

    For a simple register/login
    Code:
    Imports System.ComponentModel.DataAnnotations
    Imports ValidatorLibrary.Rules
    
    Namespace Classes
        Public Class CustomerLogin
    
            <Required(ErrorMessage:="{0} is required"), DataType(DataType.Text)>
            <StringLength(20, MinimumLength:=6)>
            Public Property Name() As String
    
            <Required(ErrorMessage:="{0} is required"), DataType(DataType.Text)>
            <StringLength(20, MinimumLength:=6)>
            <PasswordCheck(ErrorMessage:="{0} must include a number and symbol in {0}")>
            Public Property Password() As String
    
            <Compare("Password",
                     ErrorMessage:="Passwords do not match, please try again")>
            <StringLength(20, MinimumLength:=6)>
            Public Property PasswordConfirmation() As String
    
        End Class
    End Namespace
    In the above class a custom rule is used to check if a password has letters, numbers and symbols

    Code:
    Imports System.ComponentModel.DataAnnotations
    Imports System.Text.RegularExpressions
    
    Namespace Rules
        Public Class PasswordCheck
            Inherits ValidationAttribute
            Public Overrides Function IsValid(value As Object) As Boolean
                Dim validPassword = False
                Dim reason = String.Empty
                Dim password As String = If(value Is Nothing, String.Empty, value.ToString())
    
                If String.IsNullOrWhiteSpace(password) OrElse password.Length < 6 Then
                    reason = "new password must be at least 6 characters long. "
                Else
                    Dim reSymbol As New Regex("((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})")
                    If Not reSymbol.IsMatch(password) Then
                        reason &= "Your new password must contain at least 1 symbol character and number."
                    Else
                        validPassword = True
                    End If
                End If
    
                If validPassword Then
                    Return True
                Else
                    Return False
                End If
    
            End Function
    
        End Class
    
    End Namespace
    Implementation in a form to capture user name, password and confirm password
    Code:
    Imports ValidatorLibrary.Classes
    Imports ValidatorLibrary.LanguageExtensions
    Imports ValidatorLibrary.Validators
    
    Public Class LoginForm
        Private _retryCount As Integer = 0
        Private Sub LoginButton_Click(sender As Object, e As EventArgs) _
            Handles LoginButton.Click
    
            Dim login As New CustomerLogin With
                    {
                        .Name = UserNameTextBox.Text,
                        .Password = PasswordTextBox.Text,
                        .PasswordConfirmation = PasswordConfirmTextBox.Text
                    }
    
            Dim validationResult As EntityValidationResult =
                    ValidationHelper.ValidateEntity(login)
    
            If validationResult.HasError Then
                If _retryCount >= 3 Then
                    MessageBox.Show("Guards toss them out!")
                    Close()
                End If
                MessageBox.Show(validationResult.ErrorMessageList())
                _retryCount += 1
            Else
                Dim f As New MainForm(login.Name)
                f.Show()
                Hide()
            End If
        End Sub
    End Class
    Screenshot depicting a invalid registration against rules in the customer login class

    Name:  F1.png
Views: 195
Size:  12.4 KB

    Passwords do not match
    Name:  F2.png
Views: 188
Size:  11.3 KB

  2. #2
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    990

    Re: Data annotation for window forms input validation

    Nice work, what is the minimum framework required?
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

  3. #3

    Thread Starter
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,484

    Re: Data annotation for window forms input validation

    Quote Originally Posted by coolcurrent4u View Post
    Nice work, what is the minimum framework required?
    Hello,

    I always write for the current Framework, don't try to make it available for earlier Frameworks so I can not say for sure. A safe answer is 4.5 Framework while the code may possibly run under 3.5.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width