Click here to Skip to main content
15,879,535 members
Articles / Web Development / ASP.NET
Article

Regular Expression Validator Web Service

Rate me:
Please Sign up or sign in to vote.
3.80/5 (9 votes)
25 Feb 20033 min read 115.1K   251   22   2
This is a simple web service that can be used to validade a regular expression.

Sample Image - RegExpService1.gif

Introduction

I think that after an introduction of RegularExpressionValidator ASP.NET server control, the use of regular expressions for validating contents like an E-mail address, zip codes, etc., is a great idea.

Sometimes you need a fast way to validate your regular expression, but you can lose a little bit time to create a simple project for RegExp class and then validate your expression.

This article a simple, but useful web service to validate a regular expression.

The code

So, let's stop talking and go to the code :)

First of all, we need to import two namespaces:

VB
Imports System.Web.Services
Imports System.Text.RegularExpressions

Now we'll create a WebMethod to validate a regular expressions using the default parameters of RegExp constructor, this WebMethod is called SimpleMatch:

VB
<WebMethod(Description:="Simple method to parse a regular _
            expression over a string and return the result")> _    
Public Function SimpleMatch(ByVal pattern As String,_
            ByVal toMatch As String) As String
    Dim mRegExp As Regex
    Try
        mRegExp = New Regex(pattern)
        If mRegExp.IsMatch(toMatch) Then
            Return "It´s match."
        Else
            Return "No match."
        End If
    Catch exp As Exception
        Return "Exception occured: " & exp.ToString()
    Finally
        mRegExp = Nothing
    End Try
End Function

The WebMethod above will return a string "It's match.", when the pattern matches a valid content else WebMethod returns "No match."

Now, we'll create a little bit more complex WebMethod to validate a regular expression using RegexOptions enumerator.

My suggestion is create a class inside the web service to set regular expression pattern parameters, like this:

VB
Public Class RegOptions
    Public IgnoreCase As Boolean
    Public ECMAScript As Boolean
    Public ExplicitCapture As Boolean
    Public IgnorePatternWhitespace As Boolean
    Public MultiLine As Boolean
    Public RightToLeft As Boolean
    Public SingleLine As Boolean
End Class

Now add a private property to work with RegOptions Class:

VB
Private _mOptions As RegexOptions
 
Private Property mOptions() As RegexOptions
    Get
        Return _mOptions
    End Get
    Set(ByVal Value As RegexOptions)
        _mOptions = Value
    End Set
End Property

The private sub DefineOptions receives an instance of RegOptions class, get all parameters information and put that in _mOptions property.

VB
Private Sub DefineOptions(ByVal Options As RegOptions)
    If Options.IgnoreCase Then mOptions = RegexOptions.IgnoreCase _
                                                          Or mOptions
    If Options.ECMAScript Then mOptions = RegexOptions.ECMAScript _
                                                          Or mOptions
    If Options.ExplicitCapture Then mOptions = RegexOptions.ExplicitCapture _
                                                          Or mOptions
    If Options.IgnorePatternWhitespace Then mOptions = _
                                      RegexOptions.IgnorePatternWhitespace _
                                                          Or mOptions
    If Options.MultiLine Then mOptions = RegexOptions.Multiline _
                                                          Or mOptions
    If Options.RightToLeft Then mOptions = RegexOptions.RightToLeft _
                                                          Or _mOptions
    If Options.SingleLine Then mOptions = RegexOptions.Singleline _
                                                          Or mOptions
End Sub

Now we can create a MatchWithOptions WebMethod to validate our regular expression with options. Like SimpleMatch WebMethod, this will return a string "It's match.", when the pattern matches a valid content else return "No match."

VB
<WebMethod(Description:="Parse a Regular Expression with _
                                 a configured parameters")> _
Public Function MatchWithOptions(ByVal pattern As String, ByVal _
         toMatch As String, ByVal MyOptions As RegOptions) As String
    Dim mRegExp As Regex
    Try
        Call DefineOptions(MyOptions)
        mRegExp = New Regex(pattern, mOptions)
        If mRegExp.IsMatch(toMatch) Then
            Return "It´s match."
        Else
            Return "No match."
        End If
    Catch exp As Exception
        Return "Exception occured: " & exp.ToString()
    End Try
End Function

Using the code

To use the RegExpService SimpleMatch WebMethod, you don't need to create a console or GUI application, just call a WebService and click over SimpleMatch WebMethod:

Image 2

I'll use it to validate an E-mail address:

Image 3

When you click on the Invoke button the pattern and string are sent to Web service and then the Web service returns the result of the regular expression validation. In the example above I put a valid E-mail address, so the result is:

Image 4

But when I put an invalid E-mail address the result is:

Image 5

Now for testing the MatchWithOptions WebMethod we need to create a simple application (Console, WindowsForm or WebForm), 'cause this WebMethod has a class as a parameter.

So we need to create a simple Windows Forms application to use both SimpleMatch and MatchWithOption WebMethods, like that:

Image 6

Then add a Web reference to RegExpService:

Image 7

Now, the RegExpService is available in a GUI application.

Image 8

Let's add a code to call the WebMethods.

Inside Form class, add to private properties:

VB
Private mRegExpService As RegExpService.RegExpService
Private mregOptions As RegExpService.RegOptions

The code for btnSimpleMatch_Click:

VB
Private Sub btnSimpleMatch_Click(ByVal sender As System.Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles btnSimpleMatch.Click
    Try
        Me.Cursor.Current = Cursors.WaitCursor
        mRegExpService = New RegExpService.RegExpService()
        MessageBox.Show(CType(mRegExpService.SimpleMatch( _
                                 Me.txtSPattern.Text, _
                                 Me.txtStoMatch.Text), String), _
                                 Me.Text)
    Catch exp As Exception
        MessageBox.Show(exp.ToString, Me.Text)
    Finally
        Me.Cursor.Current = Cursors.Default
        mRegExpService.Dispose()
    End Try
End Sub

The code for btnMatchWithOptions_Click:

VB
Private Sub btnMatchWithOptions_Click(ByVal sender As System.Object, _
                                          ByVal e As System.EventArgs) _
                                          Handles btnMatchWithOptions.Click
    Try
        Me.Cursor.Current = Cursors.WaitCursor
        mRegExpService = New RegExpService.RegExpService()
        mRegOptions = New RegExpService.RegOptions()

        With mRegOptions
            .IgnoreCase = Me.cbxIgnoreCase.Checked
            .ECMAScript = Me.cbxEMCAScript.Checked
            .ExplicitCapture = Me.cbxExplicitCapture.Checked
            .MultiLine = Me.cbxMultiLine.Checked
            .RightToLeft = Me.cbxRightToLeft.Checked
            .SingleLine = Me.cbxSingleLine.Checked
            .IgnorePatternWhitespace = Me.cbxIgnorePatternWhitespace.Checked
        End With

        MessageBox.Show(CType(mRegExpService.MatchWithOptions( _
                                  Me.txtMPattern.Text, _
                                  Me.txtMtoMatch.Text, _
                                  mRegOptions), String), _
                                  Me.Text)
    Catch exp As Exception
        MessageBox.Show(exp.ToString, Me.Text)
    Finally
        Me.Cursor.Current = Cursors.Default
        mRegExpService.Dispose()
    End Try
End Sub

The GUI application now has the entire code to use both WebMethods, so let's test MatchWithOptions WebMethod:

Image 9

The simple expression above will validate a string that starts with a character between "a" and "z" always uppercase. The text to match is "A" (uppercase) so the result is:

Image 10

But if you check the regular expression option IgnoreCase, the result will be "It's match", 'cause the pattern will ignore case when validating a string.

Image 11

Image 12

Points of interest

This is a small Web service to provide a fast and simple way to validate regular expressions. If you like to use a more robust GUI application to build and test regular expressions, I recommend the Expresso Tool provided by Jim Hollenhorst available in CodeProject.

Well, as I said before: "I think that when you use Web Services technologies, there are no limits for your applications, you just need to be creative ;-)".

History

  • 2/26/2003 - First release.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect Sky Brasil
Brazil Brazil
Ricardo Martins
.NET Architect
Brazil

Comments and Discussions

 
Questionreg exp match Pin
Amit K Bhagat5-Jun-08 23:53
Amit K Bhagat5-Jun-08 23:53 
GeneralLibrary Pin
Andre Nazare26-Feb-03 16:14
Andre Nazare26-Feb-03 16:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.