I had been doing a type check for Double for an input field on a web page but now I need to allow commas. Can this be done using a CompareValidator or do I need to use a regex validator?
Rather than using Type="Double"
, try using Type="Currency"
. It should accept values with and without commas, however it will not accept more than 2 decimal places.
Here's an example:
<asp:TextBox runat="server" ID="TextBox1" />
<asp:CompareValidator runat="server" ID="cValidator" ControlToValidate="TextBox1"
Type="Currency" Operator="DataTypeCheck" EnableClientScript="true"
ErrorMessage="Invalid format!" Display="Dynamic" />
Otherwise a RegularExpressionValidator
would work, coupled with a RequiredFieldValidator
to validate empty entries (the regex validator doesn't prevent empty entries). You could use a CustomValidator
, but you would need to come up with a client side validation routine in JavaScript if you don't want to rely solely on server side validation with a postback. Also, the client side solution may involve regex and it's more work to validate overall, although not too complicated.
This is an example using the RegularExpressionValidator
:
<asp:TextBox runat="server" ID="TextBox1" />
<asp:RequiredFieldValidator runat="server" ID="rfValidator" Display="Dynamic"
ControlToValidate="TextBox1" ErrorMessage="Required!" />
<asp:RegularExpressionValidator ID="reValidator" runat="server"
ControlToValidate="TextBox1"
EnableClientScript="True"
ErrorMessage="Invalid Format!"
Display="Dynamic"
ValidationExpression="(\d{1,3}(,\d{3})*\.\d{2})|(\d+(\.\d{2})?)" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With