Search code examples
c#validationoctal

Validate octal number


Is this a valid way to validate if a string contains only octal numbers?

public static bool IsOctal(String toCheck)
{
    if (toCheck.Contains(" "))
    {
        return false;
    }
    int parsedtoCheck;
    var parseOk = int.TryParse(toCheck, out parsedtoCheck);
    if (!parseOk)
    {
        return false;
    }
    if (Convert.ToInt32(toCheck, 8) != parsedtoCheck)
    {
        return false;
    }
    return true;
}

Solution

  • It's not at all clear what your current approach is trying to achieve, as it's converting in both decimal and octal. If you just want to check whether the string only contains digits 0-7, it's probably simplest to use a regex:

    using System;
    using System.Text.RegularExpressions;
    
    class Test
    {
        public static void Main(string[] args)
        {
            // Do you want this to be valid or not?
            Console.WriteLine(IsOctal(""));
            Console.WriteLine(IsOctal("012"));
            Console.WriteLine(IsOctal("890"));
            Console.WriteLine(IsOctal("abc"));
            // Do you want this to be valid or not?
            Console.WriteLine(IsOctal("-0123"));
        }
    
        private static bool IsOctal(string text)
        {
            return Regex.IsMatch(text, "^[0-7]+$");
        }
    }
    

    This assumes that:

    • You're only interested in non-negative values (so we don't need to accept a leading -)
    • An empty string should not be deemed valid
    • You don't need the actual value afterwards - it can be as long as you like