Skip navigation

A Clean, Well-Validated Space

Use RegularExpressionValidator to account for leading and trailing spaces in field validation.

Hot Tip

LANGUAGES: C#

ASP.NET VERSIONS: 1.0 | 1.1

 

A Clean, Well-Validated Space

Use RegularExpressionValidator to account for leading and trailing spaces in field validation.

 

By Jeff Prosise

 

Next to RequiredFieldValidator, RegularExpressionValidator is perhaps the most useful - and most used - of all the ASP.NET validation controls. The canonical use for RegularExpressionValidator is to ensure the text entered into an e-mail address field conforms to the format of a valid e-mail address, as demonstrated here:

 

<asp:TextBox ID="EMail" runat="server" />

<asp:RegularExpressionValidator

  ControlToValidate="EMail"

  ValidationExpression=

    "\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"

  ErrorMessage="Invalid e-mail address"

  Display="dynamic"

  RunAt="server"

/>

 

Recently I used a RegularExpressionValidator in exactly this way in an online event registration form. And an experience I had there reminded me of the old adage that you can't make software idiot-proof because the idiots are smarter than you.

 

Soon after the form was deployed, we began getting complaints from people whose e-mail addresses the form wouldn't accept, even though the e-mail addresses they entered looked perfectly valid. A quick investigation revealed the source of the problem: trailing spaces in the e-mail address field. If you use RegularExpressionValidator to validate user input and want to avoid unnecessary calls to tech support, you should account for the possibility of leading and trailing spaces and code accordingly. Here are two ways to go about it.

 

The first approach is to modify the RegularExpressionValidator to allow leading and trailing spaces, but to pair it with another validator that checks for leading and trailing spaces and displays a very specific error message if either is found. This example shows how to implement this approach by combining a RegularExpressionValidator and a CustomValidator:

 

<asp:TextBox ID="EMail" runat="server" />

<asp:RegularExpressionValidator

  ControlToValidate="EMail"

  ValidationExpression=

     " *\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* *"

  ErrorMessage="Invalid e-mail address"

  Display="dynamic"

  RunAt="server"

/>

<asp:CustomValidator RunAt="server"

  ControlToValidate="EMail"

  ClientValidationFunction=

    "__checkLeadingAndTrailingSpaces"

  OnServerValidate="CheckLeadingAndTrailingSpaces"

  ErrorMessage=

    "Leading and trailing spaces are not allowed"

  Display="dynamic" />

    ...

<script language="JavaScript">

<! -

function __checkLeadingAndTrailingSpaces (source, args)

{

    args.IsValid = !((args.Value.charAt (0) == ' ') |

         (args.Value.charAt (args.Value.length - 1) == ' '));

}

 - >

</script>

 

<script language="C#" runat="server">

void CheckLeadingAndTrailingSpaces (Object sender,

    ServerValidateEventArgs e)

{

    e.IsValid = !(e.Value.StartsWith (" ") |

        e.Value.EndsWith (" "));

}

</script>

 

Note that the expression assigned to the RegularExpressionValidator's ValidationExpression property now specifically allows leading and trailing spaces. If such spaces are present, however, the CustomValidator flags them.

 

The second - and more user-friendly - approach is to modify the RegularExpressionValidator to allow leading and trailing spaces, but to strip them from the input upon submission. The .NET Framework's String.Trim method makes removing leading and trailing spaces easy. With this approach, neither end users nor tech support are forced to spend valuable time on unwanted spaces. That's a win no matter which side you're on.

 

Jeff Prosise is author of several books, including Programming Microsoft .NET (Microsoft Press). He also is a co-founder of Wintellect (http://www.wintellect.com), a software consulting and education firm that specializes in .NET. Got a question for this column? Submit queries to [email protected].

 

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish