views:

188

answers:

3

Here is the code which woks perfectly and validate to enter only digits in a TEXT BOX. Now i have a problem there. My problem is i need to enter decimal values there. So i need to enter 'DOT' in the TEXT BOX. This validation has been done by using ASCII values. I even use the ASCII value of 'DOT -> 249, 250'. But it doesn't work. Any help will be appreciated.

function enterNumerics(e)
{        
    if (!e) var e = window.event;

    if(!e.which) key = e.keyCode; 

    else key = e.which; 

    if((key>=48)&&(key<=57)||key==8||key==9||key==32||key==45 || key==43)
    {
            key=key; 
            document.getElementById('bal').innerHTML ='';
            return true;
    }
    else
    {
       document.getElementById('bal').innerHTML =
            "&nbsp;&nbsp;Please Enter Numerical Values ";
       return false;
    }
}

Thanks in Advance.....

+2  A: 

You can use regular expressions instead:

function validate(){
    var val=document.getElementById("field").value; //Field value 
    if(/^[0-9\.]+$/.test(val)){    
      document.getElementById('bal').innerHTML='';    
      return true; 
    }else{    
      document.getElementById('bal').innerHTML="  Please Enter Numerical Values ";    
      return false; 
    }
}

then you call the validate function with onKeyPress event

mck89
thanks for your support mck89
Fero
A: 

Using a masked input solves the problem and enhances the solution.

There is a jQuery-Plugin available which can do that.

Bdiem
Have to say that masked inputs always confuse people. They're a brilliant idea, it's just that most people get stuck because they're used to free text.
Neil Barnwell
+1  A: 

The dot key is 46, just allow it in the if statement.

Oh, you're getting keyCode, not charCode so this is on keydown, not keypress. Ignore the above -- dot is 190.

nexus
thanks nexus.. i entered the code wrongly.. exact code is 190. you're right... thanks man...
Fero