Tuesday, April 17, 2007

Javascript function to check valid decimal value with specified digits after decimal point

    Below is the function that validates only positive decimal numbers in text box. You can specify number of digits that can be allow after decimal point.

 

var DigitsAfterDecimal = 8;
function
CheckUnit()
{

if(document.getElementById
("TextBoxName").value == '' )
{
alert("Please enter valid decimal
value");

return false;
}
else
{

if(isNaN(document.getElementById
("TextBoxName").value))
{
alert("Please enter valid decimal
value")
;


return false;
}
else
{
var val = document.getElementById
("TextBoxName").value;
if(val.indexOf(".") > -1)
{

if(val.length - (val.indexOf
(".")+1) >
DigitsAfterDecimal)
{
alert("Please enter valid
decimal value. Only " +
DigitsAfterDecimal + "
digits are allowed after
decimal.")
;



return false;
}
else
{
return true;
}
}
else
{
if(parseInt(val) > 0)
{
return true;
}
else
{
alert("Value must be
greater than 0"
);

return false;
}
}
}
}
}
Happy Programming !!

4 comments:

vk said...

hi good one, I think if(val.length - (val.indexOf
(".")+1) >
DigitsAfterDecimal)
{
alert("Please enter valid
decimal value. Only " +
DigitsAfterDecimal + "
digits are allowed after
decimal.");



return false;
}
else
{
return true;
}
can be changed
to
else
{
if(parseInt(val) > 0)
{
return true;
}
else
{
alert("Value must be
greater than 0");

return false;
}

other wise it is allowing values like -1.1 etc
}

Unknown said...

wonderful code. thanks it helped me lot

Anonymous said...

but ur code doesnt validates 1212.12.1 kind of numbers though they are not valid decimal numbers
can u please include that too

am waiting for ur reply

thanq

Anonymous said...

how about validating in exponential form
.2e-10