checking numeric in javascript - javascript

I want to show the 'valid' message if the variable value is
not numeric with length of 10
an empty string ("")
if(isNaN(num) && num !="" && num.length!=10)
{
alert("invalid");
}
else
{
alert("valid");
}
But this code shows 'digits which length is not 10' as valid. But whether it is numeric or not numeric, if its length is not 10 it should be invalid.

Your Condtion placement is wrong here.
isNaN(num) && num !=""
here, for num=1234,isNaN is false(that means it is number), but the num!="" will give true resulting in Invalid alert.
Solution
replace && with || for OR condtion.

Did you mean this:
if(is_nan(num) && num !="" && num.length<10)
{
alert("invalid");
}
else
{
alert("valid");
}
Otherwise if length is <9 or >10, you will get false.
In this case you will alert valid when your num is non-numeric, nun-empty string with length >= 10.

Related

Alert windows for second function not popping up

I'm working on an assignment where I have to write a basic program that generates a random password based on certain criteria. I have written the following snippet of code to receive input from the user regarding the minimum and maximum values of the desired password length.
`
function writePassword() {
var passwordText = document.querySelector("#password");
passwordText.value = password;
function exit(){
return;
}
function numbersOnly(num){
return /^[0-9]+$/.test(num); //checks if input only contains numbers
}
function getPassMin() {
let passMin = prompt("Input the minimum length of your password in characters (If blank, defaults to minimum length of 8):");
if (passMin < 8 && passMin !== "" && passMin !== null) { //checks if value is at least 8, reprompts if not
alert("Sorry, the password must be at least 8 characters.");
getPassMin();
} else if (passMin > 128) { //checks if value is not more than 128, reprompts if not
alert("Sorry, the password cannot exceed 128 characters.");
getPassMin();
} else if (passMin == "" || (numbersOnly(passMin) === false && passMin !== null)) {
alert("Please input a valid number in numeric format.");
getPassMin();
} else if (passMin === null){ //terminates program if cancel is pressed
writePassword.exit();
}
}
function getPassMax() {
let passMax = prompt("Input the minimum length of your password in characters (If blank, defaults to maximum length of 128):");
if (passMax > 128 && passMax!== "" && passMax !== null) { //checks if value is not more than 128, reprompts if not
alert("Sorry, the password cannot exceed 128 characters.");
getPassMax();
} else if (passMax < 8) { //checks if value is at least 8, reprompts if not
alert("Sorry, the password must be at least 8 characters.");
getPassMax();
} else if (passMax == "" || (numbersOnly(passMax) === false && passMax !== null)) { //checks if value is not blank and does not contain any non-numeric characters, reprompts if not
alert("Please input a valid number in numeric format.");
getPassMax();
} else if (passMax < passMin){ //checks if value of getPassMax is not less than getPassMin, reprompts if not
alert("Maximum value cannot be less than minimum length. You specified the minimum length as " + passMin + " characters.");
getPassMax();
} else if (passMax === null){ //terminates program if cancel is pressed
writePassword.exit();
}
}
getPassMin();
getPassMax();
}
`
The prompts in the getPassMin() method all work as expected, however the getPassMax() method only returns the proper prompt if the input value is either greater than 128 or less than 8, i.e the first 2 conditions. All the others simply result in closing the dialog window. I am not currently receiving any errors at any point during execution. Am I missing something?
I have tried copying and reusing the code from the getPassMin() method, and I have also tried re-writing the code from scratch. No success with either.
Your method getPassMax() cannot see the variable passMin which is causing an error. You could declare the variable passMin outside the scope of both methods, set the value inside getPassMin() and then it can be read inside getPassMax().
Also, be careful. When you've checked the value from the prompt is not null or empty (and against your number pattern or use if (!isNaN(value)) { ... }) then you should convert the value to a number. Currently you are comparing numbers inside strings which won't give you correct results.
You can simply use let value = Number(input); and input will be converted to a number. Now your number comparisons will be correct.

How to tell if "123#231.23" is not a number in javascript?

parseInt("123#231.23") returns 123, which is a number.
There are tons of functions out there to detect if something is a number or not already, but they all depend on parseInt.
What is another generic way of detecting that this is not an integer without using regex?
if (isNaN("123#231.23"))
{
alert("IsNaN - not a number");
}
else
{
alert ("it is a number");
}
I'm assuming that OP need to distinguish if input is a number or not. If input is float or integer looks irrelevant to his problem.
Maybe, I'm wrong...
EDIT:
Alright, to keep everyone happy, integer in javasript is pretty big.
How big integer is in javascript check here.
Asking if something is integer is asking is it a whole number between 9007199254740992 and -9007199254740992. Wholeness of the number you may check using modulus %
$("#cmd").click(function (e) { ChectIfInteger( $("#txt").val() ) });
function ChectIfInteger(myval){
if (isNaN(myval)){
alert("not integer (not number)")
}
else{
//it is a number but it is integer?
if( myval % 1 == 0 ){
if (myval <= 9007199254740992 && myval >= -9007199254740992)
{
alert("it is integer in javascript");
}
else{
alert ("not integer");
}
}
else{
alert("nope, not integer");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt"/>
<input type="button" id="cmd" value="test input">
Convert back to String and compare:
String(parseInt("123"))=="123" // true
String(parseInt("123.sdfs"))=="123.sdfs" //false
If you really want to check "for valid integer" you must combine isNaN with something else like this:
function isValidInteger(numberToTest) {
return !(isNaN(numberToTest) || String(parseInt(numberToTest)) !== numberToTest.toString());
}
This will evaluate like:
console.log(isValidInteger('123#231.23')); // false
console.log(isValidInteger('123231.23')); // false
console.log(isValidInteger('12323')); // true
console.log(isValidInteger(1e-1)); // false
console.log(isValidInteger('1e-1')); // false
And this work even with numbers.
Here is PLNKR to test.
I think this is the best way to test for integers:
function isInt(str) {
if (typeof str !== 'number' && typeof str !== 'string') {
return false;
}
return str % 1 === 0;
}
Just note that strings / numbers like "123.0" evaluates to true.
Here's yet another one that doesn't rely on string stuff:
function looksLikeInteger(n) {
return +n == n && +n === ~~n;
}
Probably should be called "looksLikeJavaScriptInteger" because it only works for 32-bit integers. It coerces to numeric with unary + and then checks for equality (so ugly strings and objects are tossed out there) and then checks to make sure that the numeric value doesn't change when coerced to an integer.

Number Validation Not Working

I have an input field thats only supposed to take numbers inbetween 1 and 4. If the number is inbetween 1 and 4, it runs some code. If not, it shoots an alert that tells the user to try again with a number between 1 and 4. Here is my code
var number = document.getElementById("num").value;
if(Number(number) === 1 || Number(number) === 2 || Number(number) === 3 || Number(number) === 4 ){
//success code here///
}
else if(Number(number) !== 1 || Number(number) !== 2 || Number(number) !== 3 || Number(number) !== 4) {
} alert("Please type a whole number between(and including) 1 and 4 into the input field.");
I learned that the '.value;' function returns a string, even if the value is a number. So I put the var 'number' in the Number(); function that converts it to a number.
The problem is, when I type 1 into the input field. It shoots the alert even though it equals 1. None of the other numbers work either. I checked the console, and there are no syntax errors(also according to DreamWeaver). Help would be highly appreciated :)
I think you made a simple mistake of putting your alert outside the else if clause.
However there are a few other things you can do to make that a little more readable and efficient.
// Call Number() here so you only have to do it once
var number = Number(document.getElementById("num").value);
// You can also do something like parseInt(document.getElementById("num").value)
// Now check to see if Number() or parseInt() actually parsed an integer out of their input
// and then check that if it's outside your number range
if (isNaN(number) || number < 1 || number > 4) {
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
} else {
// Do Successful code
}
we can write like this also
var patt1 = /[1-4]/g;
if(patt1.test(number)){
//success code here///
}
else{
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
}

javascript form validation textfield length

i got a problem on validate the student ID, it require 10 numbers, the problem i met is when i key in a valid student ID, it still return false. Please help me to check mycoding, thank you very much.
example of my Student ID = "1101106363"
if ((document.appsub.id.value == "") || !(isNaN(document.appsub.id.value)) || (document.appsub.id.value.length < 11))
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
update: [link]http://jsfiddle.net/rVswq/1/
You need to use document.getElementById method to select the element properly.
var el = document.getElementById("yourid");
if (!(isNaN(el.value)) || (el.value.length &lt 11))
{
alert("Please enter the correct Student ID");
el.focus();
return false;
}
There is something strange here.
You are checking if the value is null, OR if it IS a number (isNaN returns true if the value IS NOT a number, if you place !isNaN the result is true if the value IS a number), OR if the length is inferior to 11.
If you want to be sure that the inserted value is not null, a number and its length inferior to 11 you should write
if ((document.appsub.id.value == "") || isNaN(parseInt(document.appsub.id.value)) || (document.appsub.id.value.length > 10))
It looks to me like you don't need the NOT operator
if ((document.appsub.id.value == "") || isNaN(document.appsub.id.value) || (document.appsub.id.value.length < 11))
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
Your IF statement is wrong. You want:
if ( (document.appsub.id.value == "") || (isNaN(document.appsub.id.value)) || document.appsub.id.value.length < 11) )
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
Your if statement will catch students ids with length less to or equal to 10.
Test against length like 10 instead

Really basic javascript, checking a condition using || (or)

I am very new to JavaScript, and trying to learn using lynda.com.
I'm currently playing around with the if statement.
The code in question:
var value = prompt("1 or 2?");
if ( value == 1 ) {
alert("You have chosen 1.");
}
if ( value == 2 ) {
alert("You have chosen 2.");
}
if ( value != (1 || 2) ) {
alert("Invalid number. Try again.");
}
This is what i want to happen: If the number is NOT 1 or 2, i want JS to execute this piece of code:
if ( value != (1 || 2) ) {
alert("Invalid number. Try again.");
}
Apparently this is not the correct way to write it out, and i've tried writing it a bunch of different ways. Can someone show me the correct way, possibly using the else statement?
if ( value != 1 && value != 2) {
alert("Invalid number. Try again.");
}
If you write value != (1||2), the (1||2) will get first evaluated to 1 and then compared to value, so you effectively wrote:
if ( value != 1 ) { [...] }.
This is because the () have a higher predence than !=. You can also read this explanation about operator predence which gives more details.
1
if ( value != 1 && value !=2 ) {
alert("Invalid number. Try again.");
}
2
if ( !(value == 1 || value ==2) ) {
alert("Invalid number. Try again.");
}
3
if ( value == 1 ) {
alert("You have chosen 1.");
}
else if ( value == 2 ) {
alert("You have chosen 2.");
}
else {
alert("Invalid number. Try again.");
}
The best way to write this statement would be as follow:
if ( value == 1 )
{
alert("1");
}
else if ( value == 2 )
{
alert("2");
}
else
{
alert("no 1 or 2");
}
The if statement that you are messing on is (1 || 2)
What will happen is it will do a Boolean test and return 1.
it should look like this
if ( value !== 1 && value !== 2 )
{
alert("no 1 or 2");
}
Thanks
As already noted, the best is to separate into two NOT statements,and evaluate both:
if ( value != 1 && value != 2) ) {
alert("Invalid number. Try again.");
}
However, you could also use the if, else if, else pattern to cover yourself against all other inputs (letters, punctuation, whitespace, etc). The else acts as a catch-all at the end:
var value = prompt("1 or 2?");
if ( value == 1 ) {
alert("You have chosen 1.");
}
else if ( value == 2 ) {
alert("You have chosen 2.");
}
else {
alert("Invalid number. Try again.");
}
Inline statements like: (1 || 2) only evaluate the right hand side of the || if the left hand side is false-y. So what your statement actually is saying is:
if ( value != 1 )
Because 1 evaluates to true.
As most others have pointed out, what you actually want to do is:
if ( value != 1 && value != 2 )
The logic is incorrect. You have to do in this way
if ( value != 1 && value != 2) ) {
alert("Invalid number. Try again.");
}
the (1||2) statement is evaluated as 1 so you are testing if value != 1
have tried writing
if(value != 1 && value != 2)
You have to do it like
if ( value != 1 && value != 2 ) {
alert("Invalid number. Try again.");
}
OR
if (!(value == 1 || value == 2)) {
alert("Invalid number. Try again.");
}
You can use switch as follows
switch(value) {
case 1:
alert("You have chosen 1.");
break;
case 2:
alert("You have chosen 2.");
break;
default:
alert("Invalid number. Try again.");
}
Your problem is here:
if ( value != (1 || 2) )
What ths is doing is checking if "value" is not equal to (1 OR 2), where (1 OR 2) is evaluated first, because it's in the brackets. (1 OR 2) evaluates to 1, since 1 is truthy in javascript. What your code is actually doing is checking if your value is not equal to 1.
What you actually want to do is check if your value is !=1 and that your value is !=2. You do that like this:
if (value !=1 && value !=2) { /* do something */ }
You don't need a clause. You can just use:
else{
}

Categories

Resources