Cena Ebrahimiyan
Cena Ebrahimiyan

Reputation: 23

regex masked input for latitude and longitude with jquery

I'm trying to mask an input specifically for latitude and longitude values with jQuery. I started searching for a regex value to validate each of them, and hopefully I found these:

for latitude
/^-?([0-8]?[0-9]|90)\.[0-9]{1,6}$/
for longitude
/^-?((1?[0-7]?|[0-9]?)[0-9]|180)\.[0-9]{1,6}$/

Also I found a function to mask an input with regex as below:

$(this).keypress(function(event){
    if(!event.charCode){
        return true;
    }
    var part1 = this.value.substring(0,this.selectionStart);
    var part2 = this.value.substring(this.selectionEnd,this.value.length);
    if(!mask.test(part1 + String.fromCharCode(event.charCode) + part2)){
        return false;
    }
});

Now when I check values like /^-?([0-8]?[0-9]|90)\.[0-9]{1,6}$/.test("44.4") the validation returns true but what I want to accomplish here is to validate these inputs as the user is typing.

For example I start by inputting 4:

/^-?([0-8]?[0-9]|90)\.[0-9]{1,6}$/.test("4") returns false;

and therefore the input gets no value.

Upvotes: 1

Views: 1704

Answers (2)

user557597
user557597

Reputation:

Latitute: /^(?:-|-?(?:\d|[1-8]\d?|90?)(?:\.[0-9]{0,6})?)$/

 ^ 
 (?:
      - 
   |  
      -? 
      (?:
           \d 
        |  [1-8] \d? 
        |  90?
      )
      (?: \. [0-9]{0,6} )?
 )
 $

Longitude: /^(?:-|-?(?:\d|[1-9]\d?|1(?:[0-7]\d?)?|1(?:80?)?)(?:\.[0-9]{0,6})?)$/

 ^ 
 (?:
      - 
   |  
      -?     
      (?:
           \d 
        |  [1-9] \d? 
        |  1 
           (?: [0-7] \d? )?
        |  1
           (?: 80? )?
      )
      (?: \. [0-9]{0,6} )?
 )
 $  

24 Hour Time: ^(?:\d|0\d?|1\d?|2[0-3]?)(?::(?:\d|0\d?|[1-5]\d?)?)?$

 ^     
 (?:
      \d                  #  0 -  9
   |  0 \d?               # 00 - 09
   |  1 \d?               # 10 - 19
   |  2 [0-3]?            # 20 - 23
 )
 (?:
      :                   # :
      (?:
           \d             #  0 -  9
        |  0 \d?          # 00 - 09
        |  [1-5] \d?      # 10 - 59
      )?
 )?
 $

Upvotes: 1

Luboš Hemala
Luboš Hemala

Reputation: 79

In other words while the user types you want an input that would otherwise be invalid to pass? Why not just check after the input looses focus? Or you could use some sort of timer from the last key typed.

Upvotes: 0

Related Questions