The only really reliable way to validate if a string can be interpreted as some numeric type is to try parse it, for example:
bool valid = int.TryParse(myTextBox.value);
You can also estimate validity and find out problem of parsing if you use the variant of it with exception:
internal struct ValidationResult {
internal ValidationResult(double value) { this.fValue = value; }
internal ValidationResult(System.Exception exception) { this.fExcepton = exception; }
internal bool IsValid { get { return fException == null; } }
internal System.Exception Exception { return fException; }
internal double Value { return fValue; }
System.Exception fException;
double fValue;
}
ValidationResult Validate(string value) {
try {
return new ValidationResult(double.Parse(value));
} catch (Exception e) {
return new ValidationResult(e);
}
}
Same thing with
int
, etc. Using generics with primitive types is difficult, to say the least.
The solutions based on regular expressions and other ways to analyze input strings are not effective. The value can pass the check but still throw out-of-range exceptions.
—SA