In this VB.Net Tutorial/Code Example, I’m going to show you how to check whether a VAT Number is valid or not.
For this piece of code you will need to import “System.Text.RegularExpressions”
Public Shared Function isValidVATNumber(ByVal theVATNumber As String) As Boolean Dim startChar As String = "^" Dim endChar As String = "$" Dim rtn As Boolean = False Dim i As Integer = 8 Dim valString As String Dim sum As Integer = 0 'Check that the string matches the requirements rtn = Regex.IsMatch(theVATNumber, startChar & "([A-Z{2}])*(([1-9]d{8})|([1-9]d{11}))" & endChar, RegexOptions.Multiline) If rtn Then 'Now perform the validation valString = theVATNumber If Regex.IsMatch(valString, startChar & "[A-Z]{2}", RegexOptions.Multiline) Then valString = valString.Substring(2) End If While i >= 2 sum += (i * CInt(valString.Substring(0, 1))) valString = valString.Substring(1) i -= 1 End While While sum > 0 sum -= 97 End While rtn = ((sum * -1) = CInt(valString)) End If Return rtn Function
Check if a VAT Number is valid
Hi, thanks for nice example, but it works for specific countries only – e.g. see http://en.wikipedia.org/wiki/VAT_identification_number – you can see, that lots of valid VAT numbers your first regex match evaluates as false…
Jiri