Link to home
Start Free TrialLog in
Avatar of mmalik15
mmalik15

asked on

validate Textbox input for decimal values in c#

Hi,
I want to validate user input for deicmal values upto two decimal places. I dont want to  use Ajax Mased Input. Any idea
thanks
ASKER CERTIFIED SOLUTION
Avatar of tbsgadi
tbsgadi
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of oobayly
You could add a custom validator to the page, and handle the ServerValidate event
 
  protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
    decimal value;
 
    // Test for decimal
    if (!decimal.TryParse(args.Value, out value)) {
      args.IsValid = false;
      return;
    }
 
    // Test for 2 decimal places
    args.IsValid = ((value * 100) % 1 == 0);
  }

Open in new window

If you don't require users to type the decimals but only want to prevent them from inputting more than 2, you can use a CompareValidator, set the ControlToValidate to your textbox, set the Operator to DataTypeCheck and Type to Currency.
It will allow numbers like 123 | 123.0 | 123.00 | 123.99