Tuesday, July 27, 2010

ASP.Net: Clientside Date, Double, Integer,Currency Validation

When using text field date, Double type (decimal places or different decimal characters in globalization etc) and currency validation on client-side we often use regular expression validator and try to write complex regular expressions. The easiest way to validate these data types is to use compare validator. I think it’s the most powerful and awesome control for validating data types.
All you have to do is to set
Operator="DataTypeCheck"

And
Type="<<your required type here >>>"

It supports following types:
  • Date
  • Currency
  • Double
  • Integer
  • String


Look at the following examples:
  • This validates the date according to current culture of the application.

    <asp:TextBox ID="txtDateStart" CssClass="input" runat="server" Width="200"></asp:TextBox>

    <asp:CompareValidator ID="cmprValidatorDateStart" ControlToValidate="txtDateStart" Type="Date" Display="Dynamic" Operator="DataTypeCheck" ErrorMessage="*Not a valid date." runat="server"<>/asp:CompareValidator>

  • This validates double type. The plus point of using this is that for example you set the current culture to German (which uses "," as a decimal character) it also validates that correctly with no change.

    <asp:TextBox ID="txtDoubleType" CssClass="input" runat="server" Width="200"></asp:TextBox>

    <asp:CompareValidator ID="cmprValidatorDoubleType " ControlToValidate=" txtDoubleType" Type="Double" Display="Dynamic" Operator="DataTypeCheck" ErrorMessage="*Not a valid number." runat="server"<>/asp:CompareValidator>

  • This validates Currency

    <asp:TextBox ID="txtCurrencyType" CssClass="input" runat="server" Width="200"></asp:TextBox>

    <asp:CompareValidator ID="cmprValidatorDoubleType " ControlToValidate=" txtCurrencyType" Type="Currency" Display="Dynamic" Operator="DataTypeCheck" ErrorMessage="*Not a valid amount." runat="server"<>/asp:CompareValidator>



Enjoy coding....! :)