Trevor Hodgins
Trevor Hodgins

Reputation: 95

enforce constraints in VB

Last Question.

If I wanted to enforce constraints e.g. I only wanted letters or I only wanted numbers.

How would I do that?

Public Property HealthCardNumber() As String
    Get
        Return _HealthCardNumber
    End Get
    Set(ByVal value As String)
        _HealthCardNumber = value
    End Set
End Property

Thanks

Upvotes: 0

Views: 119

Answers (1)

Mike Dinescu
Mike Dinescu

Reputation: 55760

You could do it with a regular expression:

Public Property HealthCardNumber() As String
  Get
    Return _HealthCardNumber
  End Get
  Set(ByVal value As String)
    Set validatorRegex = CreateObject("VBScript.RegExp")
    validatorRegex.IgnoreCase = True
    validatorRegex.Pattern = "^[a-z0-9]+$"
    validatorRegex.Global = True

    If validatorRegex.Test(value) Then
       _HealthCardNumber = value
    Else
       ' throw invalid value exception, or do whatever you think is appropriate
    End If
  End Set
End Property

The example above would match strings of any combination of letters and/or numbers.

If you wanted only letters you could use this regex: ^[a-z]+$

If you only want number, you could use this regex: ^[0-9]+$

For other more specific cases you can look up information about regular expressions and character classes.

Upvotes: 3

Related Questions