I'm at uni and working on an assignment in c# that takes some user input (from they keyboard via console).
The input validation required:
- numbers must be within range (range will vary depending on which menu they're in)
- strings must not be empty/null
- string must be no longer than 30 characters in length
So I've chosen to write just one method (will be a static method of a 'validator' class) that can handle validation for both and am unsure if this is a good idea - having a method that essentially does more than one thing.
The method:
public static bool isValid(string input, string type, int min = 0, int max = 0) { if (String.IsNullOrEmpty(input)) return false; else { switch (type.ToLower()) { case "integer": int i; if (Int32.TryParse(input, out i)) return ((i >= min) && (i <= max)); else return false; case "string": return input.Length < charLimit; // charLimit defined as 30 above default: return false; } } }
And a sample call:
if(isValid(userInput, "integer", 0, 5) { // do something awesome }
I've run some tests to check the edge cases and passing in empty strings etc and it passed them, but for some reason this feels kind of wrong.
Should I separate string and integer validation into separate methods?