Joe Shamuraq
Joe Shamuraq

Reputation: 1385

jQuery for validating latitude and longitude regex

I'm validating using jQuery as follow:

$("#register-form").validate({
rules: {
latitude: {
    required: true,
    strongCoord: true
  },
  longitude: {
    required: true,
    strongCoord: true
  }
},
messages: {
  yrAr: {
    required: 'Please enter year.'
  }
}
});

$.validator.addMethod('strongCoord', function(value, element) {
return this.optional(element) 
  value.length >= 4
  && /^-?([0-8]?[0-9]|90)\.[0-9]{1,6},-?((1?[0-7]?|[0-9]?)[0-9]|180)\.[0-9]{1,6}$/.test(value);
}, 'Your coordinate format has error\'.')

And in the form the text fields are as follow:

input class="form-control" name="latitude" placeholder="Enter Latitude" type="text">
<input class="form-control" name="longitude" placeholder="Longitude" type="text">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.min.js"></script>

It keeps returning Your coordinate format has error'. even though i used coordinates i got from google. I'm sure its just syntax. Can anyone point me i the right direction?

Thank in advance...

Upvotes: 0

Views: 3721

Answers (2)

Joe Shamuraq
Joe Shamuraq

Reputation: 1385

Solved it... I created 2 separate functions for latitude and longitude instead of one function for both:

$.validator.addMethod('latCoord', function(value, element) {
  console.log(this.optional(element))
return this.optional(element) ||
  value.length >= 4 && /^(?=.)-?((8[0-5]?)|([0-7]?[0-9]))?(?:\.[0-9]{1,20})?$/.test(value);
}, 'Your Latitude format has error.')

$.validator.addMethod('longCoord', function(value, element) {
  console.log(this.optional(element))
return this.optional(element) ||
  value.length >= 4 && /^(?=.)-?((0?[8-9][0-9])|180|([0-1]?[0-7]?[0-9]))?(?:\.[0-9]{1,20})?$/.test(value);
}, 'Your Longitude format has error.')

Then i called it as such:

latitude: {
    required: true,
    latCoord: true
  },
  longitude: {
    required: true,
    longCoord: true
  }

It still bothers me why i can't use a single function for both :(

Upvotes: 1

duncan
duncan

Reputation: 31912

In your function you do:

return this.optional(element) 
  value.length >= 4
  && /^-?([0-8]?[0-9]|90)\.[0-9]{1,6},-?((1?[0-7]?|[0-9]?)[0-9]|180)\.[0-9]{1,6}$/.test(value);

However that doesn't look like correct syntax to me. The documentation gives an example like:

  return this.optional(element) || /^http:\/\/mycorporatedomain.com/.test(value);

I think you need to change your code to:

return this.optional(element) || 
  (value.length >= 4
  && /^-?([0-8]?[0-9]|90)\.[0-9]{1,6},-?((1?[0-7]?|[0-9]?)[0-9]|180)\.[0-9]{1,6}$/.test(value));

Upvotes: 1

Related Questions