javascriptjqueryregexjquery-inputmask

Lat/Long mask positive/negative detection


Hey all I am trying to create a mask for my 2 input boxes that will house the latitude and longitude.

Taken that the latitude can be a positive or negative number and the same goes for longitude. The issue being is that I am trying to come up with a regex that can give the user the ability to first chose if its going to be a positive or negative number then give user the mask of (-/+)XXX.XXXXXX.

However, I am not getting too close to the conclusion and so I am asking for a some help in reaching that goal.

I have set up a JSFiddle of what I have so far, which is not much, in order to archive my goal.

$('.mask').inputmask({
    regex: String.raw `^[-/*][0-9]{3}[.][0-9]{7}$`
});

The above code works for negative numbers but when typing out, say 100., it just sits there because its waiting on the - in order to begin. I thought adding the * it would allow it to input a positive number. The above should allow the user to input in the format of -XXX.XXXXXX OR XXX.XXXXXXX.

I still need to figure out how to also tell when the first part (xxx.) is only 1 or 2 digits instead of 3 which makes the user have to put in a 0's in front of said number digits.

So valid input would be like so:

-2.984593 instead of -002.984593

-74.192822 instead of -074.192822

-102.738631

7.653721 instead of +007.653721

10.746633 instead of +010.746633

110.938365

How can this be formatted in order to work as I need it to?


Solution

  • You could simply make the dash optional:

    ^-?\d{3}\.\d{7}$
    

    I took the liberty of refactoring your RegEx pattern ([0-9] -> \d, [.] -> \.).

    As for allowing the first part to be one or two digits, you could use:

    ^-?\d{1,3}\.\d{7}$