I am trying to validate user input to make sure that what they type (if anything - field is not required) is a number. Now I don't care what this number is, but it must be an integer. Negative, positive, whatever is validated later on. Here is my test sample so far:
var a=["",0,"0",-2,"-2",2,"2",-2.2,"-2.2",2.2,"2.2",-1,"-1",undefined,null,NaN,Infinity,-Infinity],x;
for(x=0;x<a.length;x++){
console.log(a[x],(isNaN(+a[x]) || Math.round(+a[x]) != +a[x] || +a[x] === null || +a[x]+1==+a[x])?false:true);
}
If you run that in a console, it shows true for any element in a which would pass the validation, false otherwise. This validation works as expected for me in Chrome (false is shown for all decimals, and everything from undefined onward.
My question is, will this work in all major browsers (IE 6+ included), and have I completely checked this against every possible input?
As a note:
+ is used in front of the a[x] for type-converting (and also trimming strings - " 2 " gets converted to 2.
The last check, +a[x]+1===+a[x] is what checks against (+/-)Infinity.
Thanks :) .
Try this function
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
alert("Is an Integer");
} else {
alert("Is not an Integer");
}
}
is_int(1); //Output - Is an Integer
is_int("a"); //Output - Is not an Integer
Related
I have problems with check prompt data. I need to check, if the prompt data will be string, paragraph could show that data is not number. But according to my code, when I enter string data, it shows me odd or even message, but not 'Not number'. What's can be wrong? Thanks a lot!
prompt() always returns a string, use parseInt(prompt(), 10) to convert it to a string (10 is the numeric base, eg.: 2 means its a binary number)
It will return either a number or a NaN (Not A Number) value.
typeof(NaN) === 'number'
NaN === NaN will result in false, use Number.isNaN to check if the value of a variable is NaN
if (!(a === b)) is the same as if (a !== b)
Please, next time post your code as text instead of a sharing print screen of it, so we can ctrl+c, ctrl+v it
Because your second if condition evaluates as:
!("nonsense" % 2 === 0)
!(NaN % 2 === 0)
!(NaN === 0)
!(false)
true
therefore it will always show Odd" for non numbers. Maybe you should validate your data before you use it. Additionally val will always be of type "string", you might want to parse it properly:
const num = parseInt(prompt("A number?"), 10);
if(isNaN(num)) {
//...
}
I am making a simple hangman game in JavaScript. I'm playing around trying to add new features and one of the features I'd like to add is to check the input the user gives (when they guess a letter of the unknown word) to make sure it is in fact an alphanumeric input (or my intention is to check that the input isn't a symbol like "!" or a number like "5").
I know I could probably use a global variable that contains all the valid characters and check the input against those characters but I was wondering if there is a built in method for this. I found the typeof operator but it seems that the types of characters I'm checking for get converted to strings by JavaScript.
The loop in which I'm trying to implement this:
while (remainingLetters > 0 && numberOfGuesses > 0) {
alert(answerArray.join(" "));
alert("You have " + numberOfGuesses + " guesses remaining.");
var guess = prompt("Guess a letter, or click \
'Cancel' to stop playing.").toLowerCase();
if (guess === null) {
break;
} else if (typeof guess === "number") {
alert("Please enter a single LETTER.");
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else {
for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;
remainingLetters--;
// there is some code missing here that I'm pretty sure is not essential
// to my question!
When I run that in Chrome's dev tools, I can input "2" and it never gives me the alert I'm looking for - it doesn't crash or anything it just re-starts the loop (which is the status quo before I tried to implement this "feature").
Thanks in advance!
The issue with this code is that prompt always returns a string value. These values may or may not be able to be converted to a Number; this conversion would be performed using parseInt or parseFloat. (If the string can be converted to a numerical value, these methods return that value; otherwise, they return NaN.) However, typeof performs no interpolation—it states the type of the variable as it exists, and not any types to which it could potentially be converted. Therefore, typeof guess will always evaluate to string. To check if a string contains a numerical value, you could use the condition if (!isNaN(parseInt(guess)) or if (!isNaN(parseFloat(guess)) (note that the isNaN method must be used instead of a traditional equality check).
However, you might want to structure your checks around ensuring that the entry is a letter rather than accounting for the myriad ways in which it might not be. For instance, # and ≥ are not numbers, but they are also not letters. Similarly, if your answerArray contains only Latin letters without diacritics, you might want to disallow guesses of characters like é and ç. Thus, consider using RegEx to check if the guessed string contains an acceptable letter. As in this Stack Overflow post, you can use the following if statement to ensure that the string is one character long and is a valid letter: if (str.length === 1 && str.match(/[a-z]/)). You can refer to that post for ways of addressing more complicated character sets (e.g., non-Latin letters or those with diacritics).
Currently working on only decimal values where in the text field user enter only deciaml value. Should accept only 10 numbers for example if user enter 12345.000000 it should get an alert says Number field format error. Please re-enter using the proper format. (6.3)
With my current jquery code it will accept decimal value
$("#txtQty").keyup(function() {
var $this = $(this);
$this.val($this.val().replace(/[^\d.]/g, ''));
});
This is my html code for the text box with this html it will allow only 10 character
<input id="txtQty" type="text" maxlength="10"/>
I tired the below SO user told but still I am getting the same issue
$('#txtQty').focusout(function(e) {
if('123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null){
alert("Number field format error. Please re-enter using the proper format. (6.3)");
}else{
'123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
}
});
before decimal point it has to accept (1-6) 6 number after decimal point it has to accept 3 only zero's if wrongly typed it should throw an alert not at all working still not getting that
Here is the fiddle link for the same
123456.000 -- true
12345.000 -- true
1234.000 -- true
123.000 -- true
12.000 -- true
1.000 -- true
Thanks in advance
$('.ipt_Havg').focusout(function (e) {
var regexp = /\d*\.\d{3}/
if (document.getElementById("ipt_Havg").value !== regexp) {
alert("Number field format error. Please re-enter using the proper format. (6.3)");
} else {
alert('nothing wrong here');
}
});
1) Your if/else is broken...
if('123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null){
alert("Number field format error. Please re-enter using the proper format. (6.3)");
}else{
'123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null // <- comparison makes no sense here
}
You are incorrectly using a comparison operator in place of a "statement" within the else. The else needs to contain a "statement" (something to do) not another comparison operator.
See: MDN "if...else" documentation
If some condition is true then do something, otherwise do something else.
if ('123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null) {
alert("Number field format error. Please re-enter using the proper format. (6.3)");
} else {
alert('nothing wrong here');
}
2) NOTE: I previously thought this was too obvious to even mention, however, you've hard coded '123456.789' into the conditional. In other words, it will never matter what value gets entered into your form...
'123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) is always going to be true since '123456.789' is the only value being used here.
Otherwise, use the value of the field...
$('#ipt_Havg').val().match(/\d*\.\d{3}/) !== null
3) Your logic was also backwards.
if ($('#ipt_Havg').val().match(/\d*\.\d{3}/) !== null) {
alert('nothing wrong here');
} else {
alert("Number field format error. Please re-enter using the proper format. (6.3)");
}
DEMO: http://jsfiddle.net/wfzv0h5y/
4) Incorrect regex...
but one small mistake in the end it has to accept only three zero not more than tht but now if i enter 1234.0000 still it was accepting
Your regex also needed fixing...
^\d{1,6}\.0{3}$
DEMO: http://jsfiddle.net/wfzv0h5y/6/
JQuery Number Formatter Plugin is a good alternative in your situation.
https://github.com/andrewgp/jsNumberFormatter
You can check your input through this and validate the way you want.
You could use HTML5 input number:
<input type='number' step='0.001' max="999999.999" />
The step= sets the decimal places, the max= guarantees the other side.
You can specify repetitions in RegExps:
'123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
true
'123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
false
I want to validate a input field. The user should type in a phone number with minimum length of 10 digits.
So I need to check for illegal chars. It would be nice just to check wheather the input is an integer or not.
I came up with this but it does not work (n would be the string).
function isInt(n){
return typeof n== 'number' && n%1==0;
}
Any ideas?
You can do a test like this:
input.length >= 10 && /^[0-9]+$/.test(input)
That will fail if there are non-digits in the string or the string is less than 10 chars long
This should work((input - 0) automatically tries to convert the value to a number):
function isInt(input){
return ((input - 0) == input && input % 1==0);
}
There is already an SO-question about this issue: Validate decimal numbers in JavaScript - IsNumeric()
Might be an overkill for you, but Google has not too long ago announced a library for phone validation. Java and Javascript variants are available.
Validating a phone number is a little more complicated than checking if the input is an integer. As an example phone numbers can and do begin with zeros so it isn't technically and int. Also users may enter dashes: For example:
00 34 922-123-456
So, as for validating it you have a couple of options:
Use regex expression to validate, have a look at:
http://regexlib.com/
this site will have hundreds of examples
Use looping to check each characters in turn, i.e. is character int or dash
I would recommend the former as the latter depends on consistent input from users and you aren't going to get that
Why not use:
return (+val === ~~val && null !== val);
as a return in your function?
this is the output of the javascript console
> +"foobar" === ~~"foobar"
false
> +1.6 === ~~1.6
false
> +'-1' === ~~'-1'
true
> +'-1.56' === ~~'-1.56'
false
> +1 === ~~1
true
> +-1 === ~~-1
true
> +null === ~~null // this is why we need the "&& null !== val" in our return call
true
I am pulling a value via JavaScript from a textbox. If the textbox is empty, it returns NaN. I want to return an empty string if it's null, empty, etc.
What check do I do? if(NAN = tb.value)?
Hm, something is fishy here.
In what browser does an empty textbox return NaN? I've never seen that happen, and I cannot reproduce it.
The value of a text box is, in fact a string. An empty text box returns an empty string!
Oh, and to check if something is NaN, you should use:
if (isNaN(tb.value))
{
...
}
Note: The isNaN()-function returns true for anything that cannot be parsed as a number, except for empty strings. That means it's a good check for numeric input (much easier than regexes):
if (tb.value != "" && !isNaN(tb.value))
{
// It's a number
numValue = parseFloat(tb.value);
}
You can also do it this way:
var number = +input.value;
if (input.value === "" || number != number)
{
// not a number
}
NaN is equal to nothing, not even itself.
if you don't like to use + to convert from String to Number, use the normal parseInt, but remember to always give a base
var number = parseInt(input.value, 10)
otherwise "08" becomes 0 because Javascript thinks it's an octal number.
Assuming you have a reference to the input text box:
function getInteger(input) {
if(!input || !input.value) return "";
var val = parseInt(input.value, 10);
if(isNaN(val)) return "";
else return val;
}
One thing you could do is a regex check on the value of the textbox and make sure it fits the format of an accepted number, and then if it fits the format perform your process, otherwise return an empty string.
Edit: This is an example from some code I have in front of me (might not be the best regular expression):
var anum=/(^\d+$)/;
if (!anum.test(document.getElementById("<%=txtConceptOrderValue.ClientID %>").value))
{
alert("Order Value must be a valid integer");
document.getElementById("<%=txtConceptOrderValue.ClientID %>").focus();
return false;
}
Edit 2: I should also note that I am using ASP.NET which is why I have the slightly funky way of accessing the textbox. In your regular JavaScript case it may not be as cluttered.