validating currency using javascript regular expression

Using javascript we can define regular expressions to validate input of an html entry box. The text entered into entry box must match with the format defined in regular expression. The built-in “test” function performs that matching. It the text is not matched, the check fails.

In the following example, we match the currency with a predefined format:

<!DOCTYPE html>
    <title>Untitled document</title>
  <meta charset="utf-8" />

    <script language="javascript" type="text/javascript">
        function validate()
            var currency = document.getElementById("txtcurrency").value;
            var currencyFormat = /^\d+(\.\d{1,2})?$/;
      if( currencyFormat.test(currency) != true)
      alert("Currency must be correct format");
      return false;
      return true;
<form id="frm" name="frm" method="post" 
      action="" onsubmit="return validate();">
    <input id="txtcurrency" name="txtcurrency" type="text" />
    <br /><br />
    <input id="btn" name="btn" type="submit" value="Submit" />


Add a Comment

Your email address will not be published. Required fields are marked *