Comparing Negative Values in Acrobat - javascript

Very, VERY new to JavaScript here.. I've been trying to make a character sheet in acrobat auto-populating, and so far I've had good success with most things, until coming to comparing two values.
MaxDex can be an integer greater than 0, and DexTempMod and DexMod can be integers between -10 and 10. The code below works great if dexTempMod and DexMod are positive - if they're greater than MaxDex, it will output MaxDex instead.
But if DexTempMod or DexMod are negative values, it still outputs MaxDex, despite the others being lower. I've tried parsing them into floats after some research, thinking they might be strings, but it still doesn't work.
If it's just a limitation of Acrobat, that's fine, but I'm a little stumped.
if (this.getField("MaxDex").value == ""){if (this.getField("DEXTempMod").value == "")
{event.value = this.getField("DEXMod").value}
else {event.value = this.getField("DEXTempMod").value};
}
else {if (Float.parseFloat(this.getField("MaxDex").value) < Float.parseFloat(this.getField("DEXTempMod").value) || Float.parseFloat(this.getField("DEXMod").value))
{event.value = this.getField("MaxDex").value}
else {if (this.getField("DEXTempMod").value == "")
{event.value = this.getField("DEXMod").value}
else {event.value = this.getField("DEXTempMod").value};}
}

You don't need to use Float.parseFloat. Just be sure the fields are formatted to be numbers in the field properties.
There's no comparison after the || in your outer else statement so any value will evaluate as true in your else statement because even an empty field has a value.

Related

While loop keep looping even though expression is false

My loop is not quitting when i enter 10. Please help me.
let getGuessess = function(){
let guessedNum = null;
while(guessedNum !== 10){
guessedNum = prompt(`enter number $`);
if(guessedNum === "quit"){
break;
}
}
}
getGuessess();
Change from !== to !=. You're doing a strict equality check on 10 vs '10'.
or !== '10'
Maybe these links can help:
https://www.w3schools.com/js/js_comparisons.asp
I see there that:
!== means not equal value or not equal type
https://www.w3schools.com/jsref/met_win_prompt.asp
And here that, for the prompt function:
Return Value: A String.
I think that it doesn't work because you are comparing a string and an int, they are different types, so your comparison returns False even if you enter 10.

Restrict text input to number groups separate by a non-consecutive character

I've been doing a lot of searching, chopping and changing, but I'm...slightly lost, especially with regards to many of the regex examples I've been seeing.
This is what I want to do:
I have a text input field, size 32.
I want users to enter their telephone numbers in it, but I want them to enter a minimum of 10 numbers, separated by a single comma. Example:
E.g. 1
0123456789,0123456789 = right (first group is >=10 numbers, second group = >=10 numbers & groups are separated by a single comma, no spaces or other symbols)
E.g. 2
0123456789,,0123456789 = wrong (because there are 2 commas)
E.g. 3
0123456789,0123456789,0123456789 = right (same concept as E.g. 1, but with 3 groups)
I've got the following, but it does not limit the comma to 1 per 10 numbers, and it does not impose a minimum character count on the number group.
$(document).ready(function(){
$("#lastname").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != ','
&& (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Preferably, I'd like to warn the user of where they are going wrong as well. For example, if they try to enter two commas, I'd like to specifically point that out in the error, or if they havent inserted enough numbers, i'd like to specifically point that out in the error. I'd also like to point out in the error when neither a number or a comma is inserted. I'd like to ensure that the tab, and F5 keys are not disabled on the keyboard as well. And very importantly, I'd like to specifically detect when the plus or addition key is used, and give a different error there. I think I'm asking for something a little complex and uninviting so sorry :/
The example code I provided above works pretty well across all browsers, but it doesn't have any of the minimum or maximum limits on anything I've alluded to above.
Any help would be appreciated.
As far as a regex that will check that the input is valid (1-3 phone numbers of exactly 10 digits, separated by single commas), you can do this:
^\d{10}(,\d{10}){0,2}$
Try like the below snippet without Regex
var errrorMessage = '';
function validateLength (no) {
if(!no.length == 10) {
return false;
}
return true;
}
function validatePhoneNumbers (currentString, splitBy) {
if(currentString) {
var isValid = true,
currentList = currentString.split(splitBy);
// If there is only one email / some other separated strings, Trim and Return.
if(currentList.length == 1) {
errrorMessage = 'Invalid Length in Item: 1';
if(validateLength( currentString.trim() )) isValid = false;
}
else if(currentList.length > 1) {
// Iterating mainly to trim and validate.
for (var i = 0; i < currentList.length; i++) {
var listItem = currentList[i].trim();
if( validateLength(listItem ) ) {
isValid = false;
errrorMessage = 'Invalid Length in Item:' + i
break;
}
// else if for some other validation.
}
}
}
return isValid;
}
validatePhoneNumbers( $("#lastname").val() );

Why is everything NOT prime?

I'm trying to write this program to find prime numbers. I have the basics of it down, except that no matter what number I put in, it returns as NOT prime. I've been messing with this for way too long and cannot figure out what it is. Is it in my "if" statement or my isPrime function? Please help, and thank you!
var number = 0;
function main()
{
number = parseInt(prompt("Please Enter a Number to Determine Whether or Not it is Prime:", "Enter a Number"));
while(isNaN(number) === true)
{ alert("You Entered an Invalid Number. Please Reenter");
number = parseInt(prompt("Please Enter a Number to Determine Whether or Not it is Prime:", "Enter a Number"));
}
isPrime(number);
if(prime = false)
{ alert("The number " + number + " is a Prime Number!"); }
else
{ alert("The number " + number + " is NOT a Prime Number!"); }
}
/*------------------------------------------------------*/
function isPrime(number)
{
if(number < 2)
{return false;}
var prime = false;
for(var i = 2; i <= Math.sqrt(number); i++)
{ if(number % i == 0)
{prime = true;}
}
return prime;
}
if (prime = false)
You just assigned prime to false.
You don't want to do that.
By contrast, you do want to assign it to the result of your function.
Replace:
if(prime = false)
not only because you're using assignment instead of comparison, but because prime is not defined (it's not going to return/create a global variable prime from that function call).
Replace it with:
if (!isPrime(number)) {
Now this doesn't use a variable to store the result of the isPrime call, but uses the call directly. If you need this result in more than one place, then it would be a good idea to assign it to a variable:
var prime = isPrime(number);
and then do the rest of your code:
if (prime == false)...
isPrime(number);
leaves no variable assigned. Therefore prime is never assigned in your test and unassigned variables are treated as false as far as boolean expressions are concerned.
It should be
var prime = isPrime(number);
You're also doing an assignment where you meant to do a comparison.
if(prime = false)
should be
if(prime === false)
Tip: If you're doing these kinds of tests, it's usually a good idea to put the thing that can't be changed by assignment on the left (function call, constant, etc). That way if you accidentally put = instead of == or === the script will fail with an error.
if(false === prime)
If you accidentally type
if (false = prime)
you'll get
ReferenceError: invalid assignment left-hand side
which is obvious and easy to debug.
As this is a simple boolean switch, a simple "is not true" check is fine.
if (!prime)
Actually their are only 2 small logic failure.
You define "prime" inside your function isPrime() - hence you cannot use it outside your function.
You try to do if(prime = false) which assigns the value false to "prime" whick does nothing for your if except breaking it.
You need to define the variable outside hence use your prime = isPrime()
Also you do not need to check against "false" which by any means does not really make sense their. "true == false" ? just skip that ans ask for if(prime) which is true or false.
Alternativly you can call your funtion directily in the if condition like:
if(isPrime(number)){....
it then automaticly checks the return value.

Comparing values with leading zeros in Javascript

I have a javascript code that compares two values:
} else if (!(parseInt($('#form_value').val()) >= 1)){
alert("Error: You didn't pick a number!");
form_value in this case is 001, and I would like to compare it to the one, but it doesn't seem to work. I have tried using parseInt but it didn't work either. Any solutions?
Try:
if (!(Number(parseInt($('#form_value').val(),10)) >= 1)){
EDIT: try this shortened version:
if ( parseInt($('#form_value').val(),10) < 1){
Well, Number("001"); returns 1 and Number("000"); returns 0
based on your comment above
"I'm trying to display an error if the value is less than 1, the
lowest value a user can submit is 000 (which is loaded by default), if
you pick something, it becomes 001."
If the lowest possible value is 0 then just test for 0...
var thing = Number($('#form_Value').val());
if (isNaN(thing) || thing === 0) {
alert('an error message')'
}
May be you should change the condition to if ( +( $('#form_value').val() ) < 1 ) or just if (!+$('#form_value').val()).

Javascript regex to validate GPS coordinates

I have a form where a user inserts the GPS coordinates of a location to a corresponding photo. Its easy enough to filter out invalid numbers, since I just have to test for a range of (-90, 90), (-180, 180) for lat/long coordinates.
However, this also means that regular text is valid input.
I've tried changing the test pattern to
var pattern= "^[a-zA-Z]"
and is used in the function to detect alphabetical characters
$(".lat").keyup(function(){
var thisID= this.id;
var num = thisID.substring(3, thisID.length);
var thisVal = $(this).val();
//if invalid input, show error message and hide save button
if (pattern.test(thisVal)){
$("#latError"+num).fadeIn(250);
$("#save"+num).fadeOut(100)
}
else { //otherwise, hide error message and show save
$("#save"+num).fadeIn(250);
$("#latError"+num).fadeOut(100);
}
});
However, this doesn't work as Firebug complains that pattern.test is not a function What would solve this issue?
This is what i use in my project:
const regexLat = /^(-?[1-8]?\d(?:\.\d{1,18})?|90(?:\.0{1,18})?)$/;
const regexLon = /^(-?(?:1[0-7]|[1-9])?\d(?:\.\d{1,18})?|180(?:\.0{1,18})?)$/;
function check_lat_lon(lat, lon) {
let validLat = regexLat.test(lat);
let validLon = regexLon.test(lon);
return validLat && validLon;
}
check_lat_lon(-34.11242, -58.11547) Will return TRUE if valid, else FALSE
I hope this will be usefull to you!
Do you need to use regex? Consider the following:
var val = parseFloat(lat);
if (!isNaN(val) && val <= 90 && val >= -90)
return true;
else
return false;
How about the pattern -?[0-9]{1,3}[.][0-9]+ then you parseInt and check the range as you said before.
test() is a method of the RegExp object - you're running it on a string, so will fail.
Enclose your pattern in a RegExp literal (/pattern/), so
var pattern= /^[a-zA-Z]/
That will get rid of the errors you're getting, but you have a separate issue with regards to a) whether your pattern is correct for what you want it to do; b) whether you need REGEX at all.
REGEX acts on strings - it cannot be used to determine whether a number is within a given range (unless that range is 0-10 inclusive).
#flem's answer shows the best way to approach what you're doing - no REGEX needed. The call to parseInt() will catch non-numeric characters since it will return NaN if the value contains any.
#paul flemming gave a great answer, this answer extends his and includes longitude and uses typescript.
I would suggest this in place of regex for speed and simplicity.
Since, parseFloat takes a string and returns a number isNaN check isn't needed. This function allows a string or a number and converts it to string for parseFloat and will then do the simple threshold tests against +-90 & +-180.
function isValidLatAndLong(lat: number |string, lon:number|string){
const num1 = "" +lat; //convert toString
const num2 = "" +lon;
if (parseFloat(num1) <= 90 && parseFloat(num1) >= -90 && parseFloat(num2) <= 180 && parseFloat(num2) >= -180){
return true;
}
else{
return false;
}
}

Categories

Resources