Search code examples
htmlforms

Html form input field - pattern attribute - allow integers and increments of 0.5


I'm building an html form and one of the fields is for a quantity/length of an item.

Valid values are anything with an increment of 0.5 - therefore 0.5, 1, 1.5, 2, 2.5

I'm having issues building a regex to put in the "pattern" attribute that will allow both the full and half entries.

I originally had this :

pattern="[0-9]+\.[0-9]"

This allows 0.5, 1.5 etc but fails on integers

I then tried this :

pattern="[0-9]+,[0-9]*\.[0-9]+"

But this fails on all entries.

Anyone got any ideas ?


Solution

  • Instead of using an input[type=text] and engage its pattern attribute, it could be better to use directly an input[type=number].

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number

    Anyway the regex to allow only integer numbers or steps of .5 would be [0-9]+(\.5)?

    input:invalid {
      border: red solid 3px;
    }
    <input type="text" pattern="[0-9]+(\.5)?">
    
    <input type="number" step="0.5" min="0">