Janet
Janet

Reputation: 1411

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).

Upvotes: 0

Views: 3821

Answers (3)

Joseph Marikle
Joseph Marikle

Reputation: 78520

/^([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

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

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.

Upvotes: 1

Anton Vidishchev
Anton Vidishchev

Reputation: 1389

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;

Upvotes: 0

Related Questions