0

So I have a little method that validates a number input based on the users browser culture. This is in asp.net webforms.

public static bool IsNumberInCulture(object source, EventArgs e) {
        TextBox validateSource = (TextBox)source;
        string validateThis = validateSource.Text.Trim();
        decimal result;

        if (validateThis.Length > 0) {
            if (decimal.TryParse(validateThis, NumberStyles.Number, UserCulture, out result)) {
                if (validateThis != result.ToString("N0", UserCulture) && validateThis != result.ToString("N1", UserCulture) && validateThis != result.ToString("N2", UserCulture)) {
                    return false;
                } else {
                    return true;
                }
            }
        }
        return false;
    }

This appears to work really well. Except with Norwegian numbers.

What is strange, is that the browser formats the number display correctly. Example. 6 000,00. If I delete and replace the numbers individually in the text box, the number validates to true. If I remove the number in the text box completely, and input a new number, using the same format (number, space, number, number, number, comma, number number) the number validates to false!!

I don't understand this. Anyone have any ideas?

AFract
  • 8,868
  • 6
  • 48
  • 70
Stuart
  • 1,544
  • 5
  • 29
  • 45
  • Is this WinForms or WPF or ...? – RenniePet Nov 25 '14 at 12:36
  • sorry, this is .net web forms. this is not a web service but a class method that is accessed globally – Stuart Nov 25 '14 at 13:44
  • When do you validate the input, when the user hits Enter or for every keystroke? – RenniePet Nov 25 '14 at 14:07
  • on text_changed, so then the user exits the field – Stuart Nov 25 '14 at 14:23
  • Are you sure? For WinForms the TextBox.TextChanged event is raised for each keystroke. If this is also the case in your environment, I can guess that at "6 0", i.e. after your third keystroke, the validation fails since that's an invalid number. http://stackoverflow.com/questions/16619225/why-my-textbox-textchanged-event-gets-fired-after-i-enter-only-one-character-i – RenniePet Nov 25 '14 at 14:41
  • i am positive. this is not a win forms project, it is a web forms project :) – Stuart Nov 25 '14 at 15:01

0 Answers0