Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to validate currency input?

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'." />    
like image 533
Abe Miessler Avatar asked Apr 22 '10 19:04

Abe Miessler


People also ask

How do you validate inputs?

Validation should aim to be as accommodating as possible of different forms of input for particular data types. For example, telephone numbers are written with different separators and digit groupings. Your form will be easier to use if it can interpret multiple notations. Also, it is helpful to be liberal with input.

What is the best approach in regards of input validation?

In general, it is best to perform input validation on both the client side and server side. Client-side input validation can help reduce server load and can prevent malicious users from submitting invalid data. However, client-side input validation is not a substitute for server-side input validation.


2 Answers

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])?$
like image 178
Alex Peck Avatar answered Sep 19 '22 07:09

Alex Peck


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.

like image 29
user323678 Avatar answered Sep 17 '22 07:09

user323678