tags:

views:

425

answers:

3

I'm using 'Amount' as a column in my datatable for my application.

I want to perform the following validations w.r.t 'Amount' which is a string variable.

1) i want to check if the amount has more than 2 digits after the decimal point

2) if the amount is positive or negative .. (as in case of negative error message needs to be flashed)

Can u help in this with short and efficient code snippets ???

+1  A: 

I quickly put a validation function together that should do what you want.

public static bool validateAmount(string amount)
{
    int posDecSep = amount.IndexOf(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
    int decimalPlaces = amount.Length - posDecSep - 1;
    if (posDecSep < 0) { decimalPlaces = 0; }
    if (decimalPlaces > 2)
    {
        //handle error with args, or however your validation works
        return false;
    }
    decimal decAmount;
    if (decimal.TryParse(amount, out decAmount))
    {
        if (decAmount >= 0)
        {
            //positive
        }
        else
        {
            //negative
        }
    }
    return true;
}
Peter
I think decimal.TryParse will fail without the second parameter, an "out" value.
Barry Fandango
You're right, I quickly put this together without seeing if it would compile. I edited the code and now it does, thanks for pointing this out.
Peter
+1  A: 

You can create a validated numeric textbox like this:

<asp:TextBox ID="txtDollars" Runat="server" />
<asp:CustomValidator 
    runat="server" 
    ErrorMessage="Only a valid number with no more than two decimal places is allowed." 
    ClientValidationFunction="validateDollars"
    />

<script type=text/javascript>
function validateDollars(source,args)
{
    // first check for a valid number
    args.IsValid = !isNaN(args.Value)
    if(args.IsValid)
    {
        // confirmed numeric, now check for 3+ decimals.
        if(args.Value.Match(/\.\d\d\d+/))
            args.IsValid = false;
    }
    return;
}
</script>
Barry Fandango
A: 

Hi,

   But checking digits after decimal shows error even for numbers of kind 1986, 200134

which are given as inputs...... what to do ???? !!!

stack_pointer is EXTINCT
I've added some validation to my answer to check when there is no decimal separator
Peter