I have a WPF application with a textbox where my user will enter a latitude value in decimal degrees (with up to 7 digits of precision). Valid latitudes range from -90.0000000 to 90.0000000, of course. I'm trying to create a regex to restrict input via the PreviewTextInput event for the textbox similar to this:
private void latitudeTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !ValidateDecimalString(e.Text);
}
public static bool ValidateDecimalString(string decimalString)
{
Regex regex = new Regex("[^0-9]+");
return !regex.IsMatch(decimalString);
}
My current regex allows only numbers to be entered but there are some other limitations that I need to enforce as well like:
Examples of valid latitude values:
Can I achieve these additional restrictions just by modifying my regex? If so, how? Thanks!
try something like this
public static bool ValidateDecimalString(string decimalString)
{
Regex regex = new Regex(@"^(-)?([0-9]+)(\.[0-9]+)?$");
return regex.IsMatch(decimalString);
}
for validate range better use converted value like
public static bool ValidateLatitudeString(string decimalString)
{
if(ValidateDecimalString(decimalString)){
double lat = 0;
return double.TryParse(decimalString, out lat) && lat<=90.0 && lat>=-90;
}
return false;
}
so possibly better will be without regex like
public static bool ValidateLatitudeString(string decimalString)
{
double lat = 0;
return double.TryParse(decimalString, out lat) && lat<=90.0 && lat>=-90;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With