Domanda

I need to parse html values for top, left, width and height.
User can input anything he want, but I need to forbid him to enter any incorrect values, like "px100" and etc.
I need to be sure that string he entered is something from this:
100px
100%
-100px
-100%

where 100 can be any number.

I tried to code it, but there is so many checks must be done, so I though maybe there is some better solution exist.

    //checks if test_str contains symbols other than allowed
    private string IsStringContainsSymbolsOtherThan(string test_str, List<char> symbols)
    {
        if (string.IsNullOrEmpty(test_str))
            return null;

        for (int i = 0; i < test_str.Length; i++)
            if (!symbols.Contains(test_str[i]))
                return test_str[i].ToString();

        return null;
    }

    //should return error saying what's wrong with entered value (NOT MUCH NEEDED)
    private string GetExceptionMsgFromIntegerValidating(string val)
    {
        if (string.IsNullOrEmpty(val))
            return "Value can't be empty.";

        List<char> allowed_symbols = new List<char>(new char[] { '-', 'P', 'p', 'X', 'x', '%', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
        string possible_bad_symbol = null;

        if (!string.IsNullOrEmpty(possible_bad_symbol = IsStringContainsSymbolsOtherThan(val, allowed_symbols)))
            return "Entered value contains unexcpected symbol \"" + possible_bad_symbol + "\".";

        if (val.Contains("-") && !val.StartsWith("-"))
            return "Negative numbers should start with minus symbol";

        if (val.EndsWith("px"))
        {
            string test_int = val.Replace("px", "");

            if (string.IsNullOrEmpty(test_int))
                return "Some digit must be entered before 'px'";

            //this is where I understand that I need to do checks in some other way, instead of hard coding all possible situations.
            //for example, user can input "100pxpx%"
        }
        else if (val.EndsWith("%"))
        {

        }
        else
            return "The value entered in incorrect format";

        return null;
    }
È stato utile?

Soluzione

This is a perfect scenario for regular expressions:

(?:^-[1-9]+px$)|(?:^[1-9]+px$)|(?:^-[1-9]+%$)|(?:^[1-9]+%$)|(?:^0$)

Take a look at Regex class documentation.

NOTE: Maybe it's not the best regular expression, but it's about giving you a starting point.

Update

Even better regular expression:

  • Just 0
  • Starts without minus sign, 1 or more numbers starting from 1 and ends with px.
  • Starts with minus sign, 1 or more numbers starting from 1 and ends withpx.
  • Starts without minus sign, 1 or more numbers starting from 1 and ends with%.
  • Starts with minus sign, 1 or more numbers starting from 1 and ends with%.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top