Validating currency input in ASP.NET

by Abe Miessler 13. September 2010 16:02

While doing some input validation for a web application I am working on I attempted to use ASP.NET's CompareValidator to do some pretty basic validation for a currency input.  I was surprised to find that it kept saying my input wasn't valid any time I included the "$" symbol.  Below is an example of how I implemented the control:

<asp:CompareValidator ID="vld_Cash" runat="server"
     ControlToValidate="CashTextBox"
     Type="Currency"
     Operator="DataTypeCheck"
     ValidationGroup="vld_Update"
     ErrorMessage="You must enter a currency for 'Cash'. Example: $500" />

Thinking that this might be some bizzare intended behavior from Microsoft I decided to take a look at the documentation.  According to Microsoft the Currency data type is:

    "A decimal data type that can contain currency symbols."

I did some more poking around and it looks like i'm not the first person to have this problem.  From what I've read the best work around for this is to create a RegularExpressionValidator that will allow input that is formatted as currency.  When creating the regular expression you will be using with your RegularExpressionValidator remember to use JScript compliant regex.  I made the mistake of using .NET regex and when it tried to validate on the client side it threw an exception.  If you create a JScript regex it should work fine on both client and server side.  Below is the RegularExpressionValidator that I ended up using to accomplish what ASP.NET's CompareValidator couldn't:

<asp:RegularExpressionValidator ID="rev_CashTextBox" runat="server"          
        ValidationExpression="^\s*\$?\s*(?!\d{4,},)(\d|\d{1,3},(?=\d{3})(?!\d{4}))*(\.\d{1,2})?\s*$"
        ControlToValidate="tb_Cash"
        ValidationGroup="vld_Edit"
        ErrorMessage="You must enter a currency value for Cash'. Examples: 100.00, $100" />

This allows for a number of different American currency formats to be submitted.

Here is a link to the bug I submitted to Microsoft, hopfully they will find a resolution soon.

Tags:

ASP.NET

Powered by BlogEngine.NET 1.6.0.0