title: JavaScript Decimal Place Restriction With RegEx
body: <p>I have some client-side validation against a text box, which only allows numbers up to two decimal places with no other input.</p>
  
  <p>This script was a basis for entering numeric values only, however it needs to be adapted so it can take a decimal point followed by only up to two decimal places.</p>
  
  <p>I've tried things such as <code>/[^\d].\d{0,2}</code>, but then the replacement call wouldn't work, and I've got no idea how to do it.</p>
  
  <h2>Code</h2>
  
  <pre><code>&lt;script type="text/JavaScript"&gt;
    function valid(f) {
      if (!/^\d*$/.test(f.value)) {
        f.value = f.value.replace(/[^\d]/g,"");
        alert("Invalid number");
      }
    }
  &lt;/script&gt;
  </code></pre>
  
  <hr>
  
  <h3>Note</h3>
  
  <p>I need to match an empty string. If an empty string is provided and the form is submitted, the value defaults back to zero.</p>