tags:

views:

19

answers:

1

Hi,

I'm working on a c# wpf application in which I want to validate user input in a textbox. I have a validation rule like this:

public class NumericRule : ValidationRule
{
    /// <summary>
    /// Checks whether a value can be converted to a numeric value.
    /// </summary>
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string input = value as string;

        //try conversion
        int result;
        var status = int.TryParse(input, NumberStyles.Any,
                                  CultureInfo.InvariantCulture, out result);

        //return valid result if conversion succeeded
        return status ? ValidationResult.ValidResult
                      : new ValidationResult(false, input + " is not a number");
    }
}

However, when entering a number with decimals like 3.5, it says the number is invalid. When entering 3,5 it is ok. I would like both numbers to be valid and if a value with a comma is entered, it is converted to a dot. Also I would like to have a maximum of 3 decimals after the dot..

Any help?

Thanks

+1  A: 

I suppose you want to parse as double. If you want both "," and "." as separators accepted, you can check with multiple cultures. Add the cultures you need to support to the list.

public class NumericRule : ValidationRule
{
    private readonly List<CultureInfo> cultures = new List<CultureInfo> {
        CultureInfo.CurrentCulture,
        CultureInfo.CurrentUICulture,
        CultureInfo.InvariantCulture
    };

    public override ValidationResult Validate (object value, CultureInfo cultureInfo)
    {
        string input = (string)value;

        bool success = false;
        foreach (CultureInfo culture in cultures) {
            double result;
            if (double.TryParse(input, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, culture, out result)) {
                int decimalPos = input.IndexOf(culture.NumberFormat.NumberDecimalSeparator);
                if (decimalPos == -1) {
                    success = true;
                    break;
                }
                if (input.Substring(decimalPos + 1).Length > 3)
                    return new ValidationResult(false, "Too many digits in " + input);
                success = true;
                break;
            }
        }
        return success ? ValidationResult.ValidResult : new ValidationResult(false, input + " is not a number");
    }
}
Athari