Mike Mike - 2 months ago 11
Vb.net Question

How to validate "### ##" number format in Visual Basic?

I need to be abble to validate user input in VB, where the user writes 5 numbers like this "### ##", 3 numbers, a gap and 2 more numbers. How do I do this the best way?

Thanks, Mike.

Answer

Regular expression? "\d{3}\s\d{3}"

For example, using a RegularExpressionAttribute

Public Class Model
     <RegularExpression( "^\d{3}\s\d{3}$", ErrorMessage:="You must enter the date as ### ##" )>_
     Public Property Data as String
        'Getter and setter logic
     End Property
End Class

using the Regex class

...
Public Function Validate( ByVal data as String ) as Boolean
     Static ValidationRegex as Regex = new Regex("^\d{3}\s\d{3}$",RegexOptions.Compiled) 

     Validate = ValidationRegex.IsMatch( data )
End Function

I think it's possible in VB6, but don't have an example for you.