Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>So i combined <strong>Michal Klouda</strong> ideas and mines and done this function:</p> <pre><code>$('input').bind('keypress paste', function(e) { var currVal = $(this).val(); var code = e.keyCode || e.which; var symbol = String.fromCharCode( code ); var regex = /[0-9\-]|[\b]/; if( !regex.test( symbol ) &amp;&amp; code != 37 &amp;&amp; code != 39 &amp;&amp; code != 46 || symbol == '%' || currVal.length &gt; 0 &amp;&amp; currVal[0] == '-' &amp;&amp; symbol == '-' || currVal.length &gt; 0 &amp;&amp; symbol == '.' &amp;&amp; currVal.indexOf( '.' ) &gt; -1 || currVal.length &lt; 1 &amp;&amp; symbol == '.' || currVal.length &lt; 2 &amp;&amp; symbol == '.' &amp;&amp; currVal[0] == '-' ){ e.preventDefault(); } }); </code></pre> <p>Some explanations:</p> <p><strong>regex = /[0-9\-]|[\b]/;</strong></p> <p>Removes all non numeric, exept dash, %, backspace symbols. Why it isn't removing % symbol, i can't find. <em>( one more place to inprove code )</em></p> <ul> <li>code != 37 // leaves left arrow</li> <li>code != 39 // leaves right arrow</li> <li>code != 46 // allows to delete code with delete button</li> <li>symbol == % // prevents from percentage symbol</li> </ul> <p>Other conditions allow you to write one dot and one dash symbol. Dash allowed only in first place, dot allowed in two conditions: with dash or without. With dash allowed from 3 position, without from 2 position, but only once. Also it prevents user to paste the code from clipboard.</p> <p>CODE TESTED:</p> <ul> <li>IE7+</li> <li>FF</li> <li>Chrome</li> <li>Safari</li> <li>Opera</li> </ul> <p>Try <a href="http://jsfiddle.net/GomatoX/wudVs/" rel="nofollow">DEMO</a></p> <p>P.S: thanks <strong>Michal Klouda</strong> for help.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload