Thursday, February 27, 2014

Two ways to validate a string against a regular expression

The .NET framework provides at least two ways to accomplish regular expression validation.  Microsoft seems to prefer you use RegExStringValidator for simple validation, but as you can see below, it is anything but simple.  I see no reason not to use the RegEx class which is much cleaner.

Use the RegExStringValidator class


Dim MyRegEx As String = "(?=.{8,})(?=(.*\d){1,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})"

Dim MyRegExValidator As New System.Configuration.RegexStringValidator(MyRegEx)

Try

    Dim StringToValidate As String = "gDLDdE12"

    If MyRegExValidator.CanValidate(StringToValidate.GetType()) Then
        MyRegExValidator.Validate(StringToValidate)
    End If

    'If no exception occurs, then the validation succeeded.
    
Catch ex As Exception

    'If an exception occurs, then the validation failed.

End Try


Use the RegEx class


Dim RegExEngine As System.Text.RegularExpressions.Regex = _
    New System.Text.RegularExpressions.Regex("(?=.{8,})(?=(.*\d){1,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})")

If RegExEngine.IsMatch(NewPassword.Text) Then
    'Validation is successful.
Else
    'Validation is not successful.
End If

Wednesday, February 26, 2014

Regular Expressions for password validation

Regular Expressions can look like Greek and be a real pain to wrap your head around, but sometimes they are necessary.  It's fairly easy to find a regular expression for common uses like email and phone numbers.  However, I didn't have much luck finding a regular expression to validate the format of a password.  This is probably because there are so many variations on what is considered an acceptable password.

By reverse engineering some Microsoft examples, I've discovered an easy way to create a regular expression for your specific password validation needs.

Let's walk through this:

What is the minimum length of the password?  Let's say 8.  So start with:

(?=.{8,})

Do you require at least one number?  If yes, then append:

(?=(.*\d){1,})

Do you require at least one capital letter?  If yes, then append:

(?=(.*[A-Z]){1,})

Do you require at least one lower case letter?  If yes, then append:

(?=(.*[a-z]){1,})

Do you require at least one "special" character?  If yes, then append:

(?=(.*\W){1,})

When we string these requirements together, we get:

(?=.{8,})(?=(.*\d){1,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})(?=(.*\W){1,})

By omitting and including the various sections, you should be able to create a regular expression that matches your application's definition of an "acceptable" password.

Wednesday, February 5, 2014

Use PowerShell to add an event log source.

Open PowerShell and Run as an Administrator.

[System.Diagnostics.EventLog]::CreateEventSource(name of source goes here, "Application")