简体   繁体   中英

Regex Expression to validate input format of Latitude and Longitude

I need to validate the just the format of the entered string for Latitude and Longitude and not if its a correct value for Latitude or Longitude.

The format Latitude 89:90:00N or 67:90:76 S and for Longitude 67:23:00E or 78:23:45W

I am using the below expression for which I am getting a false

 if (!Regex.IsMatch(currentValue, "^[0-9][0-9]:[0-9][0-9]:[0-9][0-9][N][S]$"))

                                Errors.Text = "Invalid format of Latitude;

Please correct me where am I going wrong..I need to validate if its either N or S (without case sensitivity).

You have made both N and S mandatory.

"^(?:90|[0-8][0-9]):[0-5][0-9]:[0-5][0-9][NS]$"    // latitude
"^(?:180|1[0-7][0-9]|[0-9][0-9]):[0-5][0-9]:[0-5][0-9][EW]$"  // longitude

should work. This will also reject invalid entries like 190:67:75E or 99:99:99S .

/^([0-9]{1,2}:[0-9]{2}:[0-9]{2}\s?[NS]|[0-9]{1,3}:[0-9]{2}:[0-9]{2}\s?[EW])$/i

should work

Credit to Tim Pietzcker for the ^$ . I forgot to put it in mine at the first :P

There's an error in N/S part. As well, you can make it more readable like that:

if (!Regex.IsMatch(currentValue, "^\d{2}:\d{2}:\d{2}[SN]$"))

                            Errors.Text = "Invalid format of Latitude;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM