Form Validation Example



<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Javascript Regular Expression Example 24
Fom validation example
********************************************************
*/
function calcm( )
{
var calForm = document.getElementById('form1');
var pattern1= /^\d\d*\.?\d*$/ ;
if (pattern1.test(calForm.inch.value))
{
calForm.cm.value = calForm.inch.value *2.54;
}
else {
calForm.cm.value ="Wrong Input";
}
}
//---->
</script>
</head>
<body>
<br> Inch to centimeter conversion <br />
<br />
<form method="post" id="form1" name="form1">
<table>
<tbody>
<tr>
<td><b> Enter inches :</b></td> <td> <input name="inch" size="10"></td>
</tr>
<tr>
<td>
<input id="button2" name="button2" value="Calculate cm" onclick="calcm()" type="button"></td>
<td> <input name="cm" size="10"> </td>
</tr>
</tbody></table>
</form>
</body>
</html>

Try this Example online


You can try this example online at - here .

Under normal conditions, the script gives the following output.



If however, the input is not a valid decimal input, it displays the error as follows.



Notice the pattern used to check a valid decimal input

var pattern1= /^\d\d*\.?\d*$/ ; 


One more point to note is that the dot sign is used to match any input which is not a new line. To match actual dot . , we use escaping character "\." . The decimal point is checked using "\.". Without the escaping character it will match "any character except new line".