stack_pointer is EXTINCT
stack_pointer is EXTINCT

Reputation: 2393

to perform validation for amout(price) in ASP.net

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 ???

EDIT:

@Peter:

But checking digits after decimal shows error even for numbers of kind 1986, 200134 which are given as inputs...... what to do ?

Upvotes: 0

Views: 2783

Answers (2)

Peter
Peter

Reputation: 14518

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;
}

Upvotes: 1

James Orr
James Orr

Reputation: 5135

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>

Upvotes: 2

Related Questions