Albert Ramos
Albert Ramos

Reputation: 3

How can I control decimal field to allow enter more than one point?

I have a field that I can control that not accepts letters etc. I allow to enter "." In order to input decimals. How can I control that not more than one "."?

Here my source code:

$(".allow_decimal").on("input", function(evt) {
   var self = $(this);
   self.val(self.val().replace(/[^0-9\.]/g, ''));
   if ((evt.which != 46 || self.val().indexOf('.') != -1) && 
       (evt.which < 48 || evt.which > 57)) 
   {
     evt.preventDefault();
   }
});

Upvotes: 0

Views: 85

Answers (1)

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14872

The HTML5 specification allows for a number input type. One of the attributes allowed for the number input is step which is the increments that the number may go up/down in:

<form>
<input type="number" step="0.1" />
<input type="submit">
</form>

While, yes, you can type in something like '2.25', when you try to submit the form, any HTML5 compliant browser will tell you off for it:

Screenshot

This only applies to HTML5 compliant browsers: CanIUse.com

As always - don't trust anything sent by a user - ALWAYS validate on the server ;)

Upvotes: 1

Related Questions