Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to restrict input into latitude (in decimal degrees) textbox

Tags:

c#

regex

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:

  • the latitude could be negative so I need to allow for the minus sign ("-") but only if it appears as the first character
  • the latitude can only contain a single decimal point (".")

Examples of valid latitude values:

  • 90
  • 90.0
  • -90.0000000

Can I achieve these additional restrictions just by modifying my regex? If so, how? Thanks!

like image 561
bmt22033 Avatar asked Oct 14 '25 16:10

bmt22033


1 Answers

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;
}
like image 147
Grundy Avatar answered Oct 17 '25 04:10

Grundy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!