Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to get the CompareValidator to accept numbers with commas?

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?

like image 807
Abe Miessler Avatar asked Aug 31 '10 23:08

Abe Miessler


1 Answers

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})?)" />
like image 78
Ahmad Mageed Avatar answered Sep 30 '22 13:09

Ahmad Mageed