Lat/Long mask positive/negative detection - javascript

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?

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}$

Related

Can this numeric range regex be refactored?

I need to match a number range:
-9223372036854775808 to 9223372036854775807
^(?:922337203685477580[0-7]|9223372036854775[0-7]\d{2}|922337203685477[0-4]\d{3}|92233720368547[0-6]\d{4}|9223372036854[0-6]\d{5}|922337203685[0-3]\d{6}|92233720368[0-4]\d{7}|9223372036[0-7]\d{8}|922337203[0-5]\d{9}|92233720[0-2]\d{10}|922337[0-1]\d{12}|92233[0-6]\d{13}|9223[0-2]\d{14}|922[0-2]\d{15}|92[0-1]\d{16}|9[01]\d{17}|[1-8]\d{18}|\d{0,18}|-(?:922337203685477580[0-8]|9223372036854775[0-7]\d{2}|922337203685477[0-4]\d{3}|92233720368547[0-6]\d{4}|9223372036854[0-6]\d{5}|922337203685[0-3]\d{6}|92233720368[0-4]\d{7}|9223372036[0-7]\d{8}|922337203[0-5]\d{9}|92233720[0-2]\d{10}|922337[0-1]\d{12}|92233[0-6]\d{13}|9223[0-2]\d{14}|922[0-2]\d{15}|92[0-1]\d{16}|9[01]\d{17}|[1-8]\d{18}|\d{0,18}))?$
// space for easier copy and paste
Yes, I know it sounds crazy, but there's a long story behind this. I can't figure out how to do this in JavaScript by just checking a range, because of the size of the number, and this must be accurate.
Here's the thought process in breaking this thing down. I just started with the max number and worked my way down, then worked on the negative by just adding the - in the regex. You'll obviously have to copy and paste this thing somewhere to see it all. Also, could be mistakes. Made my head nearly explode.
9,223,372,036,854,775,807
922337203685477580[0-7]
9223372036854775[0-7][0-9]{2}
922337203685477[0-4][0-9]{3}
92233720368547[0-6][0-9]{4}
9223372036854[0-6][0-9]{5}
922337203685[0-3][0-9]{6}
92233720368[0-4][0-9]{7}
9223372036[0-7][0-9]{8}
922337203[0-5][0-9]{9}
92233720[0-2][0-9]{10}
922337[0-1][0-9]{12}
92233[0-6][0-9]{13}
9223[0-2][0-9]{14}
922[0-2][0-9]{15}
92[0-1][0-9]{16}
9[01][0-9]{17}
[1-8][0-9]{18}
[0-9]{0,18}
There's a single digit different in the negative vs. positive, so you'll see where I had to basically duplicate most of this.
So a few question:
Did I do this right?
If not, what's a better way?
Can this be done without regular expressions considering the size of the number? I need to validate client-side.
Can it be refactored and still retain strict rules?
Suggestions appreciated :)
Can this be done without regular expressions considering the size of the number?
It can be done in a series of if statements using only string operations (no need to convert to numbers).
all strings that don't match [0-9]{1,19} are out
all candidates that are of length 18 or less are good
for length 19 you can work with string comparison to see if they are numerically less than your upper limit
tweak the above to take care of negative numbers
Your regex is correct.
This is a shorter version
^(?:-9223372036854775808|-?(?:\d{0,18}|(?!922337203685477580[8-9]|92233720368547758[1-9]|92233720368547759|922337203685477[6-9]|92233720368547[8-9]|9223372036854[8-9]|922337203685[5-9]|92233720368[6-9]|92233720369|922337203[7-9]|92233720[4-9]|9223372[1-9]|922337[3-9]|92233[8-9]|9223[4-9]|922[4-9]|92[3-9]|9[3-9])\d{19}))$
Regex demo
How to generate that regex without mistake:
Input max number:
9223372036854775807
Output:
9223372036854775807
922337203685477580
92233720368547758
9223372036854775
922337203685477
92233720368547
9223372036854
922337203685
92233720368
9223372036
922337203
92233720
9223372
922337
92233
9223
922
92
9
Replace last number letter
9->remove all line
8->9
7->[8-9]
6->[7-9]
5->[6-9]
4->[5-9]
3->[4-9]
2->[3-9]
1->[2-9]
0->[1-9]
Output:
922337203685477580[8-9]
92233720368547758[1-9]
92233720368547759
922337203685477[6-9]
92233720368547[8-9]
9223372036854[8-9]
922337203685[5-9]
92233720368[6-9]
92233720369
922337203[7-9]
92233720[4-9]
9223372[1-9]
922337[3-9]
92233[8-9]
9223[4-9]
922[4-9]
92[3-9]
9[3-9]
Regex [Output]
922337203685477580[8-9]|92233720368547758[1-9]|92233720368547759|922337203685477[6-9]|92233720368547[8-9]|9223372036854[8-9]|922337203685[5-9]|92233720368[6-9]|92233720369|922337203[7-9]|92233720[4-9]|9223372[1-9]|922337[3-9]|92233[8-9]|9223[4-9]|922[4-9]|92[3-9]|9[3-9]
Add these[output] to regex
(?!output)\d{19}
Will become [output2]
(?!922337203685477580[8-9]|92233720368547758[1-9]|92233720368547759|922337203685477[6-9]|92233720368547[8-9]|9223372036854[8-9]|922337203685[5-9]|92233720368[6-9]|92233720369|922337203[7-9]|92233720[4-9]|9223372[1-9]|922337[3-9]|92233[8-9]|9223[4-9]|922[4-9]|92[3-9]|9[3-9])\d{19}
Matches \d{19} <= 9223372036854775807
Add
^(?:-9223372036854775808|-?(?:\d{0,18}|[output2]))$
^(?:-9223372036854775808|-?(?:\d{0,18}|(?!922337203685477580[8-9]|92233720368547758[1-9]|92233720368547759|922337203685477[6-9]|92233720368547[8-9]|9223372036854[8-9]|922337203685[5-9]|92233720368[6-9]|92233720369|922337203[7-9]|92233720[4-9]|9223372[1-9]|922337[3-9]|92233[8-9]|9223[4-9]|922[4-9]|92[3-9]|9[3-9])\d{19}))$
Will match
-9223372036854775808 or
+/- \d{0,18} or
+/- \d{19} <= 9223372036854775807
Demo

Regex - creating an input/textarea that correctly interprets numbers

Im designing a conversion website where i perform calculations on inputted numbers and i need my input or textarea to receive and interpret numbers entered in different fashions
like:
Entry = 3,000,000.1111
Interpreted value = 3000000.1111
or
Entry = 3000000.1111
Interpreted value = 3000000.1111
and I want to include a second input for European decimal notation
(or if possible have the same input do both)
Entry = 3.000.000,1111 (comma acts a decimal, decimal as separator)
Interpreted value = 3000000.1111
I wonder how I could do this. I suspect from some of my research that I could use regex.
Also should i use an input or a textarea? I want to limit the size of the number to 40 places.
It seems the textarea Im currently using won't recognize any values after a comma when a comma is used. I realized this is due to parseFloat. So I need to remove the commas using .replace() before parsing. But what do I do in the instance of European notation where the comma IS the decimal point? I suspect I should use regex to identify if a number is in comma decimal notation or standard decimal point notation and then outline the appropriate replacement behavior based on that. Any ideas how to write regex to identify a number between .0000000001 and 1,000,000,000,000,000 by only the separator and decimal point? What about when the entry doesn't use either? 12000 for example. Any help with this would be appreciated. Using HTML5 and Javascript. I am not using a form and am new at this. This is my first web page so please be patient with my questions.
I was thinking about this:
input = //value from textarea as a string
if(/REGEX which determines that the structure of the number is N,NNN.NN/.test(input)){
input = input.replace(/\,/,""); //replace the commas with nothing
}
else if(/REGEX which determine that structure of the number is N.NNN,NN/.test(input){
input = input.replace(/\./,""); //replace the decimal point separators with nothing
input = input.replace(/\,/,".");//replace the comma decimal with a point decimal
}
else{
//input unchanged assuming is NNNN without decimal
}
number = parseFloat(input);
I want to keep the possibility open for them to enter large numbers and also to use numbers less than one to 10 decimal places. Thanks to those who contributed.
Best,RP
I believe this should handle everything:
^[1-9](?:\d{0,2}(?:([,.])\d{3})*|\d+)(?:(?!\1)[,.]\d+)?$
You're treading on complicated territory here. Also, the above RegEx does not allow for values less than "1".
Basically, the RegEx does the following:
Allows for no thousandths separators ("," or ".") but ensures if they are used that they occur in the correct places.
Allows for either "," or "." to be used as both thousandths/cents separators, but ensures that the cents separator is not the same as the thousandths separator.
Requires the string equivalent number to begin with any digit other than "0".
To implement this you could attach an event listener to your form element(s) and use JS to do a simple .test.
After reading further, I think I misinterpreted your goal originally. I assumed you simply wanted to validate these values with a RegEx. I also assumed you're trying to work with currency (ie. two decimal places). However, fret not! You can still utilize my original answer if you really want.
You mentioned input and textarea which are both form elements. You can attach a listener to these element(s) looking for the input, change, and/or keyup events. As a part of the callback you can run the .test method or some other functionality. Personally, I would rethink how you want to handle input. Also, what's your actual goal here? Do you really need to know the thousandths separator or keep track of it? Why not just disallow any characters other than the one decimal point/comma and digits?
Also, parsing numbers like .0000000001 as a float is a terrible idea. You will lose precision very quickly if you do any sort of calculations such as multiplication, division, power, etc. You're going to have to figure out a different method to do this like storing the number to the right separately and as integers instead then go from there.
I can help you if you describe what you're trying to do in better detail.

Ensure fixed number of decimal points when using Kendo formatting

I have played around with Kendo formatting. Specifically I am using kendo.format and kendo.toString()
I would like to fix the number of decimal points.
kendo.format("{0:#.#%}",22) works well, but it doesn't include a trailing zero for whole numbers. Ex: It doesn't give me 22.0%.
kendo.toString(22,"p1") can be used to ensure the decimal point, but it adds an undesirable space between the number and the percentage sign.(e.g.22 %).
Is there a way to ensure the trailing 0 in the formatted value (with no space before the percentage sign)? Or do I have to add code to remove the space manually?
I can easily remove it using a simple .replace(" ", ""), but I am just curious if there is a built in way to control it.
You can use zeros instad of the sharp symbols. Thus you ensure there will be a digit rendered even if it is not needed.
e.g.
kendo.format("{0:0.0%}",0.22)
Here is live example, Here is the documentation.

jQuery zip masking for multiple formats

I have a requirements for masking a zip field so that it allows the classic 5 digits zip (XXXXX) or 5 + 4 format (XXXXX-XXXX).
I could so something like:
$('#myZipField').mask("?99999-9999");
but the complication comes from the fact that dash should not be showing if the user puts in only 5 digits.
This is the best I came up with so far - I could extend it to auto-insert the dash when they insert the 6th digit but the problem with this would be funny behavior on deletion (I could stop them from deleting the dash but it would patching the patch and so forth, it becomes a nightmare):
$.mask.definitions['~']='[-]';
$("#myZipField").mask("?99999~9999", {placeholder:""});
Is there any out of the box way of doing this or do I have to roll my own?
You don't have to use a different plug-in. Just move the question mark, so that instead of:
$('#myZipField').mask("?99999-9999");
you should use:
$('#myZipField').mask("99999?-9999");
After all, it isn't the entire string which is optional, just the - and onward.
This zip code is actually simple, but when you have a more complex format to handle, here is how it's solved with the plugin (from the demo page):
var options = {onKeyPress: function(cep, e, field, options){
var masks = ['00000-000', '0-00-00-00'];
mask = (cep.length>7) ? masks[1] : masks[0];
$('.crazy_cep').mask(mask, options);
}};
$('.crazy_cep').mask('00000-000', options);
If you're using jQuery already, there are probably hundreds of plugins for masks etc, for example:
http://www.meiocodigo.com/projects/meiomask/
So I don't think you'd have to roll your own
When you use jQuery Inputmask plugin and you want to use 4 or 5 digit values for zip code you should use:
$('#myZipField').inputmask("9999[9]");
Why not have the field be transparent, and have a text object behind it with the form in light grey? So they see #######-#### in the background, and then rig it so the letters dissapear as they type. At that point, it suggests that they should enter a dash if they want to put the extra four, right? Then, you could just rig the script to autoinsert the hyphen if they mess up and type 6 numbers?

Javascript percentage validation

I am after a regular expression that validates a percentage from 0 100 and allows two decimal places.
Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript?
#Tom - Thanks for the questions. Ideally there would be no leading 0's or other trailing characters.
Thanks to all those who have replied so far. I have found the comments really interesting.
Rather than using regular expressions for this, I would simply convert the user's entered number to a floating point value, and then check for the range you want (0 to 100). Trying to do numeric range validation with regular expressions is almost always the wrong tool for the job.
var x = parseFloat(str);
if (isNaN(x) || x < 0 || x > 100) {
// value is out of range
}
I propose this one:
(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)
It matches 100, 100.0 and 100.00 using this part
^100(\.0{1,2})?$
and numbers like 0, 15, 99, 3.1, 21.67 using
^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$
Note what leading zeros are prohibited, but trailing zeros are allowed (though no more than two decimal places).
This reminds me of an old blog Entry By Alex Papadimoulis (of The Daily WTF fame) where he tells the following story:
"A client has asked me to build and install a custom shelving system. I'm at the point where I need to nail it, but I'm not sure what to use to pound the nails in. Should I use an old shoe or a glass bottle?"
How would you answer the question?
It depends. If you are looking to pound a small (20lb) nail in something like drywall, you'll find it much easier to use the bottle, especially if the shoe is dirty. However, if you are trying to drive a heavy nail into some wood, go with the shoe: the bottle with shatter in your hand.
There is something fundamentally wrong with the way you are building; you need to use real tools. Yes, it may involve a trip to the toolbox (or even to the hardware store), but doing it the right way is going to save a lot of time, money, and aggravation through the lifecycle of your product. You need to stop building things for money until you understand the basics of construction.
This is such a question where most people sees it as a challenge to come up with the correct regular expression to solve the problem, but it would be much better to just say that using regular expressions are using the wrong tool for the job.
The problem when trying to use regex to validate numeric ranges is that it is hard to change if the requirements for the allowed range is changes. Today the requirement may be to validate numbers between 0 and 100 and it is possible to write a regex for that which doesn't make your eyes bleed. But next week the requirment maybe changes so values between 0 and 315 are allowed. Good luck altering your regex.
The solution given by Greg Hewgill is probably better - even though it would validate "99fxx" as "99". But given the circumstances that might actually be ok.
Given that your value is in str
str.match(/^(100(\.0{1,2})?|([0-9]?[0-9](\.[0-9]{1,2})))$/)
^100(\.(0){0,2})?$|^([1-9]?[0-9])(\.(\d{0,2}))?\%$
This would match:
100.00
optional "1-9" followed by a digit (this makes the int part), optionally followed by a dot and two digits
From what I see, Greg Hewgill's example doesn't really work that well because parseFloat('15x') would simply return 15 which would match the 0<x<100 condition. Using parseFloat is clearly wrong because it doesn't validate the percentage value, it tries to force a validation. Some people around here are complaining about leading zeroes and some are ignoring trailing invalid characters. Maybe the author of the question should edit it and make clear what he needs.
I recomend this, if you are not exclusively developing for english speaking users:
[0-9]{1,2}((,|\.)[0-9]{1,10})?%?
You can simply replace the 10 by a 2 to get two decimal places.
My example will match:
15.5
5.4366%
1,43
50,55%
34
45%
Of cause the output of this one is harder to cast, but something like this will do (Java Code):
private static Double getMyVal(String myVal) {
if (myVal.contains("%")) {
myVal = myVal.replace("%", "");
}
if (myVal.contains(",")) {
myVal = myVal.replace(',', '.');
}
return Double.valueOf(myVal);
}
None of the above solutions worked for me, as I needed my regex to allow for values with numbers and a decimal while the user is typing ex: '18.'
This solution allows for an empty string so the user can delete their entire input, and accounts for the other rules articulated above.
/(^$)|(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)\.(\.[0-9]{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/
(100|[0-9]{1,2})(\.[0-9]{1,2})?
That should be the regex you want. I suggest you to read Mastering Regular Expression and download RegexBuddy or The Regex Coach.
#mlarsen:
Is not that a regex here won't do the job better.
Remember that validation msut be done both on client and on server side, so something like:
100|(([1-9][0-9])|[0-9])(\.(([0-9][1-9])|[1-9]))?
would be a cross-language check, just beware of checking the input length with the output match length.
(100(\.(0){1,2})?|([1-9]{1}|[0-9]{2})(\.[0-9]{1,2})?)

Categories

Resources