locked
RegEx- validate a range of number RRS feed

  • Question

  • how can i use regEx to validate a range of numbers and how can i make sure that only digits will be used ?

     

    for example- to validate numbers between 4 to ten i'm writing

    (4|5|6|7|8|9|10)

    but how can i make sure that no characters will be entered ?

    what is i want to use a bigger range ? like 0-100?

    thanks in advanced.

    Saturday, February 4, 2012 11:08 AM

Answers

  • I agree, while it is possible to use RegEx to do this, it would be much simpler to do something like:

    if (myNum >= 0 && myNum <= 100)
    {
     //Do something
    }
    

    As far as eliminating the potential for letters, the TryParse(), or using the char method IsDigit() or wrapping the conversion into a try / except block would all be suitable.  There are a number of other solutions, such as if this is WinForms you could catch the keys on the KeyDown event and supress them or even using a RegEx that checks to make sure everything is [0-9] in any type of application.


    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.
    Saturday, February 4, 2012 6:06 PM
  • Something like this:

       int someNum;
       if (int.TryParse(someString, out someNum)
       {
          if(someNum >= minValue && someNum <= maxValue)
          {
             //Got a number in range - do something with it
          }
          else
          {
             //It's a number but out of range
          }
       }
       else
       {
          //Non numeric some where in input
       }

    I would not use Try/Catch because this is not an exception but a bit of validation.

    PS I would not use a Regex either unless the number was something like a UK NI number i.e. AA999999A (format with mixed letters and digits)


    Regards David R
    ---------------------------------------------------------------
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.
    • Edited by Riced Saturday, February 4, 2012 6:26 PM Added PS
    • Proposed as answer by Malcolm Gibson Saturday, February 4, 2012 8:31 PM
    • Marked as answer by Leo Liu - MSFTModerator Monday, February 13, 2012 5:16 AM
    Saturday, February 4, 2012 6:23 PM
  • Hello CoverPpl,

    I'd write the validation you want to set up like this:

    using System;
    
    namespace _87a32c89_8d5b_41ef_92d3_92dff8d57382
    {
        class Program
        {
            static void Main()
            {
                string s1 = "8", s2 = "Hello World";
                Console.WriteLine("Is \"{0}\" Valid ? => {1}", s1, IsValid(s1, 4, 10));
                Console.WriteLine("Is \"{0}\" Valid ? => {1}", s2, IsValid(s2, 4, 10));
                Console.ReadKey();
            }
    
            static bool IsValid(string s, int min, int max)
            {
                int value;
                return int.TryParse(s, out value) && value >= min && value <= max;
            }
        }
    }
    
    

    Kind regards,


    My blog

    Whether you’re a construction worker, a forum moderator, or just someone that likes helping people. I think these guidelines can be helpful in keeping you helpful when being helpful.
    Saturday, February 4, 2012 11:13 PM

All replies

  • The simplest way may be to use int.TryParse() to see if it only has digits and then to test that the input is one of the valid numbers.


    Regards David R
    ---------------------------------------------------------------
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.
    Saturday, February 4, 2012 12:06 PM
  • Thanks.

    What about a way to validate a big range of numbers, like 0-100 ?

    Saturday, February 4, 2012 6:04 PM
  • I agree, while it is possible to use RegEx to do this, it would be much simpler to do something like:

    if (myNum >= 0 && myNum <= 100)
    {
     //Do something
    }
    

    As far as eliminating the potential for letters, the TryParse(), or using the char method IsDigit() or wrapping the conversion into a try / except block would all be suitable.  There are a number of other solutions, such as if this is WinForms you could catch the keys on the KeyDown event and supress them or even using a RegEx that checks to make sure everything is [0-9] in any type of application.


    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.
    Saturday, February 4, 2012 6:06 PM
  • Something like this:

       int someNum;
       if (int.TryParse(someString, out someNum)
       {
          if(someNum >= minValue && someNum <= maxValue)
          {
             //Got a number in range - do something with it
          }
          else
          {
             //It's a number but out of range
          }
       }
       else
       {
          //Non numeric some where in input
       }

    I would not use Try/Catch because this is not an exception but a bit of validation.

    PS I would not use a Regex either unless the number was something like a UK NI number i.e. AA999999A (format with mixed letters and digits)


    Regards David R
    ---------------------------------------------------------------
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.
    • Edited by Riced Saturday, February 4, 2012 6:26 PM Added PS
    • Proposed as answer by Malcolm Gibson Saturday, February 4, 2012 8:31 PM
    • Marked as answer by Leo Liu - MSFTModerator Monday, February 13, 2012 5:16 AM
    Saturday, February 4, 2012 6:23 PM
  • However, here is a regular expression that meets your criteria: ^([0-9]|[1-9][0-9]|100)$
    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.
    • Proposed as answer by TSoftware-Old Saturday, February 4, 2012 10:12 PM
    Saturday, February 4, 2012 6:34 PM
  • Great...Thanks for the help
    Saturday, February 4, 2012 9:14 PM
  • Suppose the range is 35 to 99, will the regex still work?

    Rhetorical question, no response needed. :)


    Regards David R
    ---------------------------------------------------------------
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.
    Saturday, February 4, 2012 10:19 PM
  • Suppose the range is 35 to 99, will the regex still work?

    Rhetorical question, no response needed. :)


    Regards David R
    ---------------------------------------------------------------
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.


    ^([3-9][5-9]|[4-9][0-9])$ :D

    Sorry, couldn't resist.


    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.
    Saturday, February 4, 2012 10:33 PM
  • Hello CoverPpl,

    I'd write the validation you want to set up like this:

    using System;
    
    namespace _87a32c89_8d5b_41ef_92d3_92dff8d57382
    {
        class Program
        {
            static void Main()
            {
                string s1 = "8", s2 = "Hello World";
                Console.WriteLine("Is \"{0}\" Valid ? => {1}", s1, IsValid(s1, 4, 10));
                Console.WriteLine("Is \"{0}\" Valid ? => {1}", s2, IsValid(s2, 4, 10));
                Console.ReadKey();
            }
    
            static bool IsValid(string s, int min, int max)
            {
                int value;
                return int.TryParse(s, out value) && value >= min && value <= max;
            }
        }
    }
    
    

    Kind regards,


    My blog

    Whether you’re a construction worker, a forum moderator, or just someone that likes helping people. I think these guidelines can be helpful in keeping you helpful when being helpful.
    Saturday, February 4, 2012 11:13 PM
  • Hi CoverPpl,

    How is it going now with your problem?
    If if has been resolved, could you mark some useful replies as answers?
    Thanks for your understanding.

    Have a nice day,

    Leo Liu [MSFT]
    MSDN Community Support | Feedback to us

    Thursday, February 9, 2012 7:14 AM
    Moderator