I've to make a program in javascript which would take an integer from the user it can be negative or positive but if user insert a decimal number or a character so this program should display an error message.
Can anyone help me jow to do it.

Troy III commented: An original reusable & efficient code has been given to you - you need to say "THANK YOU!" and mark your thread as "Solved!" -2

Recommended Answers

All 2 Replies

Member Avatar for stbuchok

look at using regular expressions for this.

var regex = /[0-9]+/ig;

if(!regex.test(valueTestingAgainst)){
    alert('you have an error');
}

I have not tested this code. If it doesn't work, look up how to use regular expressions in javascript, then look for a regular expression that works for your scenario.

you can use this code:

isInteger=
/*Troy III*/
function(v){v=Number(v);return(v!=v)+(v%1!=0)==0}

to write your own function with alerts and so...

Or you can check this funcion out:

integerCheck=
/*Troy III*/
function(v,err,Err){
Err={
      "0.0":"Integer value accepted",
      "1.0":"Decimals are not allowed!",
      "1.1":"Culd not convert to number!"
};
         v=Number(v); err=+(v%1!=0)+'.'+ +(v!=v); 
         err>0?alert(Err[err]):0;
         return Err[err]
}

Manual check example"
integerCheck("1.121") //will alert >>decimals not allowed...

p.s.:
But your teacher might want to know -where did you get it?!! (badly)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.