Validate that input is between 2 numbers in javascript - javascript

I am currently using Google maps and attempting to use input validation. I require the user to use a number between 0 and 20 to set as a zoom on my location.
Below is the code I am using. The first if statement works perfectly for any number over 20 but the second does not work when I use numbers like 0 and -1 (for instance.)
Any suggestions for fixing this?
function inputIsValid() {
console.log("Inside inputIsValid function");
//Check for Above 20
if (document.getElementById("txtZoom").value > 20) {
alert("Please insertAmount between 0 and 20");
document.getElementById("txtZoom").focus();
return false;
//Check for Number below 0
if (document.getElementById("txtZoom").value < 0) {
alert("Please insertAmount between 0 and 20");
document.getElementById("txtZoom").focus();
return false;
}
}
}

The problem is you nested the second check within the first, so it will never be reached. Try this:
function inputIsValid() {
var zoomValue = document.getElementById("txtZoom").value;
if (zoomValue > 20 || zoomValue < 0) {
alert("Please insertAmount between 0 and 20");
document.getElementById("txtZoom").focus();
return false;
}
}

function inputIsValid() {
$value = document.getElementById("txtZoom").value;
if (($value < 0) && ($value > 20)) {
alert("Please enter a value between 0 and 20");
return false;
}

Related

Simplify my isNaN function for two input variables - JavaScript

i have two variable i am getting through two prompts. One is startNum the other is rangeNum. I am trying to error catch it so that if they are not positive numbers, it will reprompt the user until a postive value is given. Currently i have this working by running an isnan for each vaiable, but im wondering if I can just have one function that checks for both prompts whether the number entered is positive, and also if not, it will reprompt the correct prompt to the user. Thanks in advance for any help/answers.
function isPosNum() {
startNum = parseInt(prompt("Please enter a positive starting value"));
if (isNaN(startNum)) {
return NaN;
} else if (startNum < 0) {
console.log('failed');
alert('That is not a positive number. Please try again and enter a positive number.');
return "negative";
isPosNum();
} else if ( startNum > 0) {
console.log('worked');
//push initial value to the array
numArray.push(startNum);
//enterRange();
return "positive";
} else {
return "zero";
}
function enterRange() {
rangeNum = parseInt(prompt("Please enter a number to determine the range of values."));
if (isNaN(rangeNum)) {
return NaN;
} else if (rangeNum < 0) {
console.log('failed');
alert('That is not a positive number. Please try again and enter a positive number.');
return "negative";
enterRange();
} else if ( rangeNum > 0) {
console.log('worked');
//push initial value to the array
//collatz();
return "positive";
} else {
return "zero";
}
}
}
I was able to get the code working thanks to deamentiaemundi's answer. Here is my final code for those who wish to see.
function getStartNum(){
startNum = parseInt(prompt('Please enter a starting number greater than 0.'));
if(!isPosNum(startNum)){
alert("error! That is an incorrect value. Please renter an appropriate positive value.");
getStartNum();
} else {
getRangeNum();
}
}
function getRangeNum(){
rangeNum = parseInt(prompt('Please enter a range value greater than 0'));
if(!isPosNum(rangeNum)){
alert("error! That is an incorrect value. Please renter an appropriate positive value.");
getRangeNum();
}
// and so on
}
function isPosNum( number ) {
if (isNaN( number )) {
return false;
} else if (number < 0) {
return false;
} else if (number == 0) {
return false;
} else {
return true;
}
}
Make a function checkRange(number) which takes the number as an argument and returns either true or false depending on that number.
The second function is the one with the prompts in it.
function getNumbers(){
startNum = parseInt(prompt('Please enter a number'));
if(!checkRange(startNum)){
alert("error!");
getNumbers();
}s
rangeNum = parseInt(prompt('Please enter a range'));
if(!checkRange(rangeNum)){
alert("error!");
getNumbers();
}
// and so on
}

JavaScript, how to validate if string?

I'm working on a form where my user enters a number between 0-100.
If my user puts in 101, it will return with an alert saying that the numbers are invalid. But how do I validate so he doesn't put in something like "asdfasdf" or if it's just empty?
This is my Validate Script:
function validate() {
var pct = $('#pct').val();
if (pct !== "" && (pct > 100 || pct < 0))
return false;
else
return true;
}
Try this:
function validate() {
var pct = parseInt($('#pct').val());
return (pct <= 100) && (pct >= 0);
}
parseInt('not a number') -> NaN
Comparison result with NaN is always false. So try represent expression as positive and play with it.

How to get alerts for inputed name length of characters - javascript

Hello im trying to do a simple script here when i enter name in input field, i want to get certain alerts for example:
- if name is > 20 characters alert = "name is bigger than 20"
- if name is between 12 and 20 alert = exact number of chars of the name that was inputed
- if name is bigger than 2 chars and bigger or equal than 20 = alert that name
this was just an example of what im trying to do, but im just noob at this point im only 1 month into javascript(html and css) so if anyone can point me in the right direction i would appreciate.
Ok, so far i have this:
<form name="myForm" id="form2" onsubmit="return validate()">
Input name: <input type="text" name = "myName" id="t" />
<input type="submit" name="submit" value="submit" />
</form>
function validate() {
if(document.myForm.myName.value.length>20){
alert("your name is too big");
submitFlag=false; // im not sure what this line does //
} else if(document.myForm.myName.value.length=12-20){
alert("your name is" + document.myForm.myName.value.length + " chars");
} else if(document.myForm.myName.value.length=0){
alert("input name")
}else{
alert("ok e")
}
return submitFlag;
}
THe if statements are workin only if i have two, im getting only the first 2 alerts, so i would like to input more else if statements and to get alerts for them also, i tried to put some more myself, but the dont work, im only getting the first two.
Extending what #dfsq have said,.. you try to get:
if name is between 12 and 20
that means smth like:
document.myForm.myName.value.length > 12 && document.myForm.myName.value.length <= 20
And make your code more simple and readable. And don't forget to return false (your submitFlag):
function validate() {
var len = document.myForm.myName.value.length;
if (len > 20)
{
alert("your name is too big");
}
else if (len > 12 && len <= 20)
{
alert("your name is" + len + " chars");
}
else if (len == 0)
{
alert("input name");
}
else
{
//in fact it would alert when name between 0 and 12
alert("ok e");
}
return false;
}
There are a difference between operators. = is an assignment, == and === are comparison operators. You need latter:
document.myForm.myName.value.length == 0
Here we go:
function validate() {
var charLength = document.myForm.myName.value.length,
submitFlag = false; // This flag would be used further to stop the use going ahead from this particular validation
if (charLength > 20) {
// length more than 20
alert("your name is too big");
} else if (charLength <= 20 && charLength > 12) {
// length between 20 and 12
alert("your name is" + charLength + " chars");
} else if (charLength == 0) {
// If no input there
alert("enter name");
} else {
// Otherwise in success condition
alert("ok e");
submitFlag = true;
}
return submitFlag;
}
Jsfiddle: http://jsfiddle.net/fcwbkkd7/

Javascript - Find if number is positive or negative

I see other solutions to my question but none that help me.
I want to create a function to find if a number is positive/negative. The function should take an integer argument and return true if the integer is positive and false if it is negative.
Also, prompt the user again and again if anything other than a number is entered
Here's the code so far
When I enter a number, it keeps alerting me it is true or false but won't let me enter another.
How do I control my loop so I can ask until -1 is entered? It is not giving me a chance to enter -1
function isPositive(num) {
var result;
if (num >= 0) {
result = true;
} else if (num < 0) {
result = false;
}
return result;
}
var num;
num = parseInt(prompt("Enter a number"));
while (num != -1) {
alert(isPositive(num));
if (isNaN(num)) {
alert("No number entered. Try again");
num = parseInt(prompt("Enter a number"));
isPositive(num);
while (num != -1) {
alert(isPositive(num));
}
}
}
There's a few things wrong with your code, so here's a rewrite with comments:
function isPositive(num) {
// if something is true return true; else return false is redundant.
return num >= 0;
}
// when you want to keep doing something until a condition is met,
// particularly with user input, consider a while(true) loop:
var num;
while (true) {
num = prompt("Enter a number");
// check for null here
if (num === null) {
alert("No number entered. Try again.");
continue; // return to the start of the loop
}
num = parseInt(num, 10); // second argument is NOT optional
if (isNaN(num)) {
alert("Invalid number entered. Try again.");
continue;
}
// once we have a valid result...
break;
}
// the loop will continue forever until the `break` is reached. Once here...
alert(isPositive(num));
Math.sign(number)
which returns either a 1, -1 or 0
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
The number 0 is neither positive, nor negative! :P
function isPositive(num)
{
if(num < 0)
return false;
else
return true;
}
Or a simple way,
function isPositive(num)
{
return (num > 0);
}
You are testing if it isn't -1. Try this:
if(num < 0){
...IS NEGATIVE...
}else{
...IS POSITIVE...
}
This checks if it is less than or greater than 0.

jQuery function for check textbox

I’d like use jquery function that validate a input field. This input field must be used for entering 11 digit numbers that start with 0.
I tried some function but doesn’t work!
function check(mob) {
var firstnum = mob.substring(1);
alert(firstnum);
if (firstnum != "0" || mob.lenght != 11)
return false;
else
return true;
}
function check(mob) {
return mob.substring(0, 1) == '0' && mob.length == 11;
}
String Method Reference
If you want to check is it 11 digit, you should use RegExp
function check(mob) {
return mob.match(/^0\d{10}$/) != null;
}
You need to use .charAt(0) to get the first character of a string. .substring(1) will return the rest of the string minus the first character.
"01234567890".substring(1) = "1234567890"
"01234567890".charAt(0) = "0"
"01234567890".length = 11 (assuming that you have spelled "length" correctly in your code)
Edit: Since you also need to check for digits, you could use a regular expression to verify this (although the whole check could also be done with a regex)
The completed function could therefore be simplified to just:
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && /^\d+$/.test(mobileNumber);
}
Or without the regex
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && !isNaN(mobileNumber);
}
if (firstnum >= 1 || mob.lenght <= 11) //lenght spell wrong
change to
if (firstnum >= 1 || mob.length<= 11)
you can give it a try
function check(mob) {
var num = parseInt(mob);
if (mob+'' == '0'+num && mob.length == 11)
return true;
else
return false;
}
here what I am doing is that parseInt will give you exact same number without 0 if all characters are numbers, so in the condition I am just adding 0 in starting and checking with mobile number , it will do 2 validation in once , all are number starts with 0 and next validation is for length
Try using a simple regex as below
function check(mob) {
return /^0\d{10}$/.test(mob)
}
function check(mob) {
if(!isNaN(mob)){ // or use parseInt
var firstnum = mob.charAt(0);
alert(firstnum);
if (firstnum != "0" || mob.length != 11) {
return false;
} else {
return true;
}
}
}

Categories

Resources