Redwall
Redwall

Reputation: 1020

Validate 0.5 as Step Value in HTML5 Number Input

I want to have an input field which only allows to type whole numbers or .5 decimal numbers. e.g. 0, 0.5, 1, 1.5, 2, 2.5.......etc etc

I am trying to do this with a HTML5 input field as so

<input type="number" min="0" max="18" step="0.5" pattern="\d+" />

but it won't validate the number when it is on a half step of 0.5. It just stays red when clicking outside / validating.

Is this possible? I can't find similar example of how to validate for half steps. DO I need to use jQuery to achieve this?

Thanks

Fiddle Demo http://jsfiddle.net/b8NrE/906/

Upvotes: 5

Views: 17065

Answers (2)

Diwas Poudel
Diwas Poudel

Reputation: 847

You can try this: It will clear text box if step is not .5

<input type="number" min="0" oninput="validity.valid||(value='');"  step="0.5" />

Upvotes: -1

Nelson Menezes
Nelson Menezes

Reputation: 2094

Remove the pattern attribute. This is used for complex validation that requires regular expressions (and your regular expression is only matching sequences of digits). As it is, stipulating min, max, and step already define all the validation that you need:

<input type="number" min="0" max="18" step="0.5" />

http://jsfiddle.net/b8NrE/907/

Upvotes: 19

Related Questions