Best way to validate currency input?

11,088

Solution 1

The CompareValidator doesn't support currency symbols. You can prefix your input control with the $ or use a regular expression validator, this page has an example.

The following pattern will match your examples (courtesy of http://www.regexlib.com):

^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$

Solution 2

Also, you could write a custom validator to parse the string, with or without $. But you would need to write some Javascript to get any client side validation.

Share:
11,088
Abe Miessler
Author by

Abe Miessler

Software Engineer who works with Javascript/Node.js, Python, C#, Go, SQL Server, MongoDB, MySQL and a whole lot more. I enjoy learning new technologies when they are the best tool for the job. I usually fill the role of a full stack engineer but always seem to enjoy working with data the most. 80th recipient of the Gold SQL badge 50th recipient of the Gold SQL Server badge Hobbies include web application security and machine learning.

Updated on June 11, 2022

Comments

  • Abe Miessler
    Abe Miessler almost 2 years

    I have created the TextBox and CompareValidator below which I thought would allow input in the following forms:

    • 5
    • 5.00
    • $5.00

    Unfortunately it's not allowing the version with the dollar sign in it. What is the point of doing a type check against currency if you don't allow the dollar sign? Is there a way to allow this symbol?

                <asp:TextBox ID="tb_CostShare" runat="server" Text='<%# Eval("CostShare", "{0:$0.00}")%>' CausesValidation="true" />
                <asp:CompareValidator   ID="vld_CostShare" 
                                        runat="server" 
                                        ControlToValidate="tb_CostShare" 
                                        Operator="DataTypeCheck" 
                                        Type="Currency" 
                                        ValidationGroup="vld" 
                                        ErrorMessage="You must enter a dollar amount for 'Cost Share'." />