title: Validate number type inputs with jQuery
body: <p>I am having a quite complex problem dealing with jQuery validation on optional fields that have the <code>type="number"</code> specified. What happens is that the browser (Chrome in this case) allows the user to enter normal letters in the field, with the idea of intercepting the submitting of the form and anyway, when the field value is queried, it will return an empty string.</p>
  
  <p>Before going forward, I must say that this is kind-of in line with the <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#number-state-%28type=number%29" rel="nofollow">specs</a>, that states:</p>
  
  <blockquote>
    <p>User agents must not allow the user to set the value to a non-empty string that is not a valid floating-point number.</p>
  </blockquote>
  
  <p>and later on:</p>
  
  <blockquote>
    <p>The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then <strong>set it to the empty string</strong> instead.</p>
  </blockquote>
  
  <p>Here lies the problem: if I enter letters in an optional number input fields (and Chrome allows that), the jQuery validation gets an empty string value which validates correctly since the field is optional. Moreover, I get the emtpy string server side which is ok since the field is nullable in the DB and happily gets saved.</p>
  
  <p>For the time being, the only workaround that I can think of is this:</p>
  
  <pre><code>$('input[type="number"]').keypress(function (evt) {
      if (evt.keyCode &lt; 48 || evt.keyCode &gt; 57)
          evt.preventDefault();
  });
  </code></pre>
  
  <p>Problem is that the above does not work, for example, if the user copy-pastes some wrong input there. Now, I realize that if the user is so determined to enter dumb data he can only face the consequences and have that field nullified, but trying to be a good developer I was wondering if there is a way of obtaining the value entered without using the workarond above (and also without writing another workaround for copypaste).</p>