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'." />
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])?$
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.
精彩评论