Thursday, March 17, 2011

ASP.NET validate values input with comma

When user input integer or float values, sometimes they will include comma in the value. For example, instead of inputting "123456", they might input "123,456". However, the Asp.net comparevalidator will not recognize comma and will give user an error message. To fix it, I use a Regulare Expression validator. Here is the regular expression:


"(-)*[0-9]+(,[0-9]+)*(.[0-9]+)*"

And the ASP.NET tags:
<asp:TextBox runat="server" ID="txtValue"></asp:TextBox>

<asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator1" ErrorMessage="Value has to be number." Display="Dynamic" ForeColor="Red" ControlToValidate="txtValue" ValidationExpression="(-)*[0-9]+(,[0-9]+)*(.[0-9]+)*"></asp:RegularExpressionValidator>

Here is the compare validator which will only work with int/float values without comma
<asp:CompareValidator runat="server" ID="cvValue" ErrorMessage="Value has to be number." Display="Dynamic" ForeColor="Red" ControlToValidate="txtValue" Operator="DataTypeCheck" Type="Double"></asp:CompareValidator>


Happy programming~

No comments:

Post a Comment