ChaseHardin
ChaseHardin

Reputation: 2269

Adding String Length Validation

I am adding validation to my text string. It allows string and integer values, which is correct, but I want to require my text to be greater than 4 characters long. I've added the text.Length > 4 but this does not add any validation when entering a 2 character string. Any suggestions?

public bool IsStringInvalid(string text)
        {
            if (String.IsNullOrEmpty(text))
            {
                if (text != null && !Regex.IsMatch(text, textCodeFormat) && text.Length > 4)
                {
                    return true;
                }
            }
            return false;
        }

Upvotes: 1

Views: 8575

Answers (3)

Iffat Fatima
Iffat Fatima

Reputation: 1748

You are checking for not null condition nested inside the null condition which is logically wrong. You should do something like this.

public bool IsStringInvalid(string text)
        {

                if (text != null && text.Length > 4 && !Regex.IsMatch(text, textCodeFormat))
                {
                    return true;
                }

                    return false;

        }

Upvotes: 1

fcman
fcman

Reputation: 46

You have your length validation if statement nested inside your other if. If text has any data if will never reach the nested if as it will fail the first since IsNullOrEmpty will return false.

I would do something like

if (String.IsNullOrEmpty(text) || !Regex.IsMatch(text, textCodeFormat) || text.Length < 4)
{
    return true;
}
return false;

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156459

Your method is called IsStringLengthInvalid, which implies that it should be returning true for invalid strings. Right now, it appears you're trying to return true only for valid strings.

Something like this should work:

    public bool IsStringInvalid(string text)
    {
        return string.IsNullOrEmpty(text) ||
            text.Length <= 4 ||
            !Regex.IsMatch(text, textCodeFormat);
    }

Upvotes: 3

Related Questions