JavaScript, how to validate if string? - javascript

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.

Related

If/Else Statement

Hi what am I doing wrong with this if statement? Ive tried making the second one and else if and the last one an else as well but cant get the alerts to respond properly.
prompt("Please enter a number");
if(x < 100) {
alert("variable is less 100")
}
if(x == 100) {
alert("variable is equal to 100!")
}
if(x > 100) {
alert("variable was greater than 100")
}
thanks!
You are missing an assignment to variable x.
var x = prompt("Please enter a number");
//^^^^^
Then you could use parseInt to get a integer number from the string
x = parseInt(x, 10);

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.

IsNan() function considers certain kind of strings as number - node js

I'm checking for integer values in node.js using IsNaN function.
Unexpectedly, this function validates the strings like 1E267146, 1E656716 , 914E6583 to be numbers, as these strings are exponential values. Any way to work around this? In actual scenario i wont get any exponential values.
ECMA6 defines Number.isInteger as follows:
Javascript
function isInteger(nVal) {
return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
}
but this will also accept scientific notation
console.log(isInteger(1e6));
console.log(isInteger(+"1e6"));
jsfiddle
You need to be clear as to what your definitions/expectations are.
My guess is that you may want something like this, if you are testing strings and have no limits on the max or min integer.
Javascript
function isStringNumericalInteger(testValue) {
return typeof testValue === "string" && /^[\-+]?[1-9]{1}\d+$|^[\-+]?0$/.test(testValue);
}
console.log(isStringNumericalInteger("9007199254740991"));
console.log(isStringNumericalInteger("-123216848516878975616587987846516879844651654847"));
console.log(isStringNumericalInteger("1.1"));
console.log(isStringNumericalInteger("-1.1"));
console.log(isStringNumericalInteger("1e10"));
console.log(isStringNumericalInteger("010"));
console.log(isStringNumericalInteger("0x9"));
console.log(isStringNumericalInteger(""));
console.log(isStringNumericalInteger(" "));
console.log(isStringNumericalInteger());
console.log(isStringNumericalInteger(null));
console.log(isStringNumericalInteger([]));
console.log(isStringNumericalInteger({}));
Output
true
true
false
false
false
false
false
false
false
false
false
false
false
jsfiddle
If you want to bound the range to what javascript can represent numerically as an integer then you will need to add a test for && +testValue > -9007199254740992 && +testValue < 9007199254740992
If you don't like using RegExs, you can also accomplish this with a parser. Something like this:
Javascript
function isCharacterDigit(testCharacter) {
var charCode = testCharacter.charCodeAt(0);
return charCode >= 48 && testCharacter <= 57;
}
function isStringNumericalInteger(testValue) {
var start = 0,
character,
index,
length;
if (typeof testValue !== "string") {
return false;
}
character = testValue.charAt(start);
if (character === "+" || character === "-") {
start += 1;
character = testValue.charAt(start);
}
start += 1;
length = testValue.length;
if ((length > start && character === "0") || !isCharacterDigit(character)) {
return false;
}
for (index = start; index < length; index += 1) {
if (!isCharacterDigit(testValue.charAt(index))) {
return false;
}
}
return true;
}
jsfiddle
I would use something like below code to validate number input. First I parse the given value to float and then check isNaN().
var isNumber = function (obj) {
return !isNaN(parseFloat(obj)) && isFinite(obj);
};
I think this is what you need in your case (i hate regex because this is not very good for the performance but..)
http://jsbin.com/EQiBada/1/
var NMAX = Math.pow(2, 53);
function isNumeric(n) {
n = n < 0 ? n * -1 : n;
var r = /^\d+$/.test(n);
if (r === true)
{
return parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX;
}
return false;
}
Minified
var NMAX = Math.pow(2, 53);
function isNumericMin(n) {
n = n < 0 ? n * -1 : n;
return /^\d+$/.test(n) === true ? parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX : false;
}
var i = '1E267146'
if(isNaN(i) || !isFinite(i) !! i=="")
{
// do stuff
}
else
{
// do stuff
}

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

Multiple Logical Operators in javascript

I want to check the following
1: Is x a number
2. If x is less that 5 or greater than 15, sound alert
3. If all is ok, callMe()
var x = 10;
if (isNaN(x) && ((x < 5) || (x > 15))) {
alert('not allowed')
}
else
{
callMe();
}
What am I doing wrong?
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}
This way, if x is not a number you go directly to the alert. If it is a number, you go to the next check (is x < 5), and so on.
All the other answers about the && vs || are correct, I just wanted to add another thing:
The isNaN() function only checks whether the parameter is the constant NaN or not. It doesn't check whether the parameter is actually number or not. So:
isNaN(10) == false
isNaN('stackoverflow') == false
isNaN([1,2,3]) == false
isNaN({ 'prop' : 'value'}) == false
isNaN(NaN) == true
In other words, you cannot use it to check whether a given variable contains a number or not. To do that I'd suggest first running the variable through parseInt() or parseFloat() depending on what values you expect there. After that check for isNaN(), because these functions return only numbers or NaN. Also this will make sure that if you have a numeric string then it is also treated like a number.
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}

Categories

Resources