Check string for integer - javascript

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

Related

Problems with prompt js typeof

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)) {
//...
}

REGEX to match only VALID EXCEL COLUMNS (A-XFD)

Ok, I have ANOTHER REGEX question for everyone.
I have a field that has multiple validation steps. The first step is to ensure it isn't blank, second is to ensure that only between 1 and 3 CAPITAL LETTERS are entered, and third, to ensure it doesn't contain "[" (an opening bracket will denote a function in this scenario and we skip validation). All of this works. Now, I have to ensure that the value being entered is only a valid Excel Column Reference. Valid Excel Columns can be the letters A - XFD.
I am currently using:
if (checkValue !==""){ //check for not blank
if ((checkValue.match(/^[A-Z]{1,3}$/) === null) && (functionCheck === false) && (validateColumnRange(rangeFrom))) { //check for only 1 - 3 alpha chars & run function check (function looks for "["), and run function check to validate column range
//do A - XFD validation here
}
}
any further direction will be much appreciated as I have been through regex tuts for hours now and am lost.
I had been given help on a similar issue in the past and my poor attempt to emulate the function that was provided then is as follows:
function validateColumnRange(valueRange) {
if (typeof valueRange !== "string" || !valueRange.length)
return false;
var startIndex = valueRange.search(/[\d+]/);
var column = valueRange.substring(0, startIndex).toUpperCase();
return (column >= "A" && column <= "XFD");
}
it doesn't work...please help
Since you've already determined that the value is 1-3 alphabetic characters, how about:
(column.length < 3 || column <= "XFD")
Any value with 2 or less letters should be acceptable, and for the case of three letters, alphabetic comparison is adequate.
Use this regex expression:
/^[A-XFD]+$/

Validating text input as a number - JavaScript

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

How to check condition in JavaScript with ASCII value?

I'm trying to do a validation for the input field and wanted to check if it's a special character or not
so I though I can check that with ASCII value but not sure how is that done in JavaScript language.
In C I can just check with the string of array right away.
if (input < 4 && document.myTable.inputField.value[0] < 65 )
I want to check if it's they have less than four character and those are special characters if yes I will give them an error message else just do nothing.
In C, brute force checking is the cleanest and easiest alternative. In JavaScript, it is not.
js> /^[A-Za-z]+$/.test('foo')
true
js> /^[A-Za-z]+$/.test('bar123')
false
You can use regular expressions. I think that's easier to read. For example: (/a-z/gi).test(myString) returns true if myString contains anything except letters (upper or lower case). So your condition can be changed to:
if (input < 4 && !(/a-z/gi).test(document.myTable.inputField.value))
You can use the charCodeAt method of String to determine the ASCII code at a certain position. Assuming that by input you mean the input field, this would be a way to do it:
var input = document.myTable.inputField.value;
if (input.length < 4 && input.charCodeAt(0) < 65 ) { /* etc. */ }
// examples charCodeAt
'foo'.charCodeAt(0); //=> 102
'-foo'.charCodeAt(0); //=> 45

How to validate for Values "0" or "00" or "000" for textfield which has the regex and some accepted values

var myregex = /^[0-9][0-9]{0,3}$|^[0-9][0-9]{0,3}[\.][0-9]$/;
if(!myregex.test($('#txt1').val()) || $('#txt1').val()=="0"){
alert("Please Enter Correct value");
}
Now My mandatory things are it should
follow Regex
we should not able to enter the value "0" or "00" or "000"
So my above if() raises an alert if the user enter a "0" and if we enter "00" or "000" or "0000" it doesnot catch it .But if we enter "00000" it catches it due to regex. How can i handle for 2,3,4 zeros .Now Here I can put a regex which doesnot accept zeros such as this one "/^[^0].*$/" but My textfield should Accepts this values as right (0.2,0.3,0.4) .so i cannot use this regex.
Avoid regex, it's a nightmare to get exactly right, and to maintain in the future. Instead, use built-in JS string parsing functionality:
var val = parseFloat($('#txt1').val());
if (isNaN(val) || (val === 0))
{
alert("Please Enter Correct value");
}
/^[1-9]\d{0,3}(?:\.\d)?$|^0\.[1-9]$/
The first alternative matches any number from 1.0 to 9999.9. The first digit has to be at least 1, which eliminates leading zeroes. The fraction part is optional ((?:\.\d)?), so it also matches integers from 1 to 9999. The second alternative handles the special cases of 0.1 through 0.9.
It looks like your regular expression requires 0 through 9999, or 0.0 through 9999.9, but you do not want to accept a 0 alone, or a series of zeros.
If that's the case, I'd say use something similar to ken's answer and process it as a float, then check that the float is above 0 and below 9999.9:
var val = parseFloat($("#txt1").val());
if(isNan(val) || val <= 0 || val > 9999.9) {
alert("Please enter a value between 0 and 9999.9");
}
If you need to use your regex and just add a check that the string doesn't consist entirely of zeroes, you can add a negative lookahead expression: (?!0+$) and enclose the alternation in a non-capturing group:
/^(?!0+$)(?:[0-9][0-9]{0,3}|[0-9][0-9]{0,3}[\.][0-9])$/
No need for Regex or any of that, quite simple.
if(('#txt1').val() < 0.1 ){
alert("Please Enter Correct value");
}
There you go, problem solved

Categories

Resources