JS Input Validation – V (Decimal Number)

A decimal or floating-point number has the following parts.

  • An integer part
  • A decimal point (‘.’)
  • A fraction part

Sometimes it is required to input a decimal number particularly for quantity, length, height, amount etc. We can have a floating-point number using optional sign (+-), integer part, and a fraction part.

 

Explanation

This is the regular expression for decimal number validation.

Regular Expression Pattern:
/^[-+]?[0-9]+(\.[0-9]+)*$/

An input validation code is given below to use the above regular expression for simple interest calculation.

 

HTML embedded JS code to calculate simple interest:

<html>
<head>
<script type="text/javascript">
function disp_alert(f)
{
var numbers = /^[-+]?[0-9]+(\.[0-9]+)*$/;

if(f.a.value.match(numbers) && f.b.value.match(numbers) && f.c.value.match(numbers))
{
var a = parseFloat(f.a.value)
var b = parseFloat(f.b.value)
var c = parseFloat(f.c.value)
f.d.value = interest(a, b, c)
return true;
}
else
{
alert("Invalid input!");
return false;
}
}
function interest(p, n, r)
{
return (p*n*r/100)
}
</script>
</head>

<body>
<center>
<form>
Enter the Principle amount(P):
<input type="text" name="a">
<br><br>
Enter the Time in months(N):
<input type="text" name="b">
<br><br>
Enter the Rate of Interest(R):
<input type="text" name="c">
<br><br>
<input type="button" onclick="return disp_alert(this.form)" value="Calculate Simple Interest"/>
<br><br>
The Simple Interest is:
<input type="text" name="d">
</form>
</center>
</body>
</html>