RegularExpressionValidator And Partial Matches

An entry about asp.net Publication date 5. July 2007 19:44

A post over at the ASP.NET forums reminded me of an odd 'feature' that the RegularExpressionValidator has - namely that it will validate to false if your regular expression pattern only matches part of the input - even though that may very well constitute a successful match. 

Say, for instance, that you have an email input field and wish to do a very* naive validation of it with the expression @, which basically states that you expect the input to have an @ character somewhere within it:

<asp:TextBox
    ID="_emailTextBox"
    runat="server" />
<asp:RegularExpressionValidator
    ID="_emailTextBoxValidator"
    runat="server"
    ValidationExpression="@"
    ControlToValidate="_emailTextBox"
    ErrorMessage="Invalid email!" />

But that won't work:

image

If you use the very same expression with the Regex class, however:

if (Regex.Match(_emailTextBox.Text, "@").Success)
{
// valid!
}

... then the input 'test@test.com' will validate to true, as expected. Now of course there's an easy fix here - change the expression to ^.*@.*$ ("match any number of characters from the beginning of the string until an @, and then any number of characters until the end of the string") and it will do what you want in both cases. But unless you know about it, its easy to spend awhile scratching your head over this one...

 

* Email address validation is very complex these days (because of a very complex spefication), and although I would recommend a 'loose' validation expression so that you don't end up blocking valid email addresses, the one in this example is perhaps a bit too simple :p

Be the first to rate this post

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.


Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS