
Untitled
By: a guest on
May 3rd, 2012 | syntax:
None | size: 1.50 KB | hits: 18 | expires: Never
Validate float number using RegEx in C#
void NumericTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsValidInput(e.Text);
}
private bool IsValidInput(string p)
{
switch (this.Type)
{
case NumericTextBoxType.Float:
return Regex.Match(p, "^[0-9]*[.][0-9]*$").Success;
case NumericTextBoxType.Integer:
default:
return Regex.Match(p, "^[0-9]*$").Success;
}
}
// And also this!
public enum NumericTextBoxType
{
Integer = 0,
Float = 1
}
@"^[0-9]*(?:.[0-9]*)?$"
var regex = new Regex(@"^[0-9]*(?:.[0-9]*)?$");
Console.WriteLine(new bool[] {regex.IsMatch("blah"),
regex.IsMatch("12"),
regex.IsMatch(".3"),
regex.IsMatch("12.3"),
regex.IsMatch("12.3.4")});
False
True
True
True
False
private bool IsValidInput(string p)
{
switch (this.Type)
{
case NumericTextBoxType.Float:
double doubleResult;
return double.TryParse(p, out doubleResult);
case NumericTextBoxType.Integer:
default:
int intResult;
return int.TryParse(p, out intResult);
}
}
public static double? TryParseInt(this string source)
{
double result;
return double.TryParse(source, out result) ? result : (double?)null;
}
// usage
bool ok = source.TryParseInt().HasValue;