Allow 2 Decimal Places In
Answer :
Instead of step="any"
, which allows for any number of decimal places, use step=".01"
, which allows up to two decimal places.
More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute
If case anyone is looking for a regex that allows only numbers with an optional 2 decimal places
^\d*(\.\d{0,2})?$
For an example, I have found solution below to be fairly reliable
HTML:
<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />
JS / JQuery:
$(document).on('keydown', 'input[pattern]', function(e){ var input = $(this); var oldVal = input.val(); var regex = new RegExp(input.attr('pattern'), 'g'); setTimeout(function(){ var newVal = input.val(); if(!regex.test(newVal)){ input.val(oldVal); } }, 0); });
Update
setTimeout is not working correctly anymore for this, maybe browsers have changed. Some other async solution will need to be devised.
For currency, I'd suggest:
<div><label>Amount $ <input type="number" placeholder="0.00" required name="price" min="0" value="0" step="0.01" title="Currency" pattern="^\d+(?:\.\d{1,2})?$" onblur=" this.parentNode.parentNode.style.backgroundColor=/^\d+(?:\.\d{1,2})?$/.test(this.value)?'inherit':'red' "></label></div>
See http://jsfiddle.net/vx3axsk5/1/
The HTML5 properties "step", "min" and "pattern" will be validated when the form is submit, not onblur. You don't need the step
if you have a pattern
and you don't need a pattern
if you have a step
. So you could revert back to step="any"
with my code since the pattern will validate it anyways.
If you'd like to validate onblur, I believe giving the user a visual cue is also helpful like coloring the background red. If the user's browser doesn't support type="number"
it will fallback to type="text"
. If the user's browser doesn't support the HTML5 pattern validation, my JavaScript snippet doesn't prevent the form from submitting, but it gives a visual cue. So for people with poor HTML5 support, and people trying to hack into the database with JavaScript disabled or forging HTTP Requests, you need to validate on the server again anyways. The point with validation on the front-end is for a better user experience. So as long as most of your users have a good experience, it's fine to rely on HTML5 features provided the code will still works and you can validate on the back-end.
Comments
Post a Comment