Friday, April 24, 2009

Case insensitive validators in .NET

I have just done some work on a control that needed to have some validation for dynamically generated text boxes. I did some poking around for adding validators dynamically that would be client side and would check for words by being case insensitive. I found a few solutions to this that involved server side validation and I wanted to keep it on the client. The ASP.NET validators use javascript on the client side and there isn't anything I could find that would easily let me do a case insensitive compare on the client side using the .NET controls. For example, I couldn't pass /sometext/i to the validator and have the 'i' attribute recognized.

A solution hit me on the way home. I was checking for the common occurences of 'true' and 'false', 'True|False|true|false'. Which was probably going to be fine but every now and then you hold the shift a second too long or you have caps lock down and you enter TRUE or FAlse and those wouldn't work out and while they would evaluate to a boolean once they hit the server, they would never get there because of the validation.

So now my expression looks like '[Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]'. that does the trick very nicely. It isn't great to read, but this is a very specific case and I've certainly seen worse. And I don't need to do a mix of server and client side validation now, which makes me happy. I wouldn't do this for something that was involved, but for this particular case it is simple to implement, not totally unreadable and prevents a useless round trip to the server.

No comments: