HTML5 input type=number change step behavior

Well, first of all thank you for this very interesting question. I’ve learned a lot about HTML5 validation by searching a solution to your problem.

My research led me to find that HTML5 form validation API has an interesting set of properties that are read-only, but very useful to do what you want.

My approach to your problem was to first add the novalidate attribute to the form element, so that I can control when to trigger the validation, then read the validity object attached to the input, so I can know exactly what validation errors are there, and if the only error is stepMismatch (this is what triggers invalidity of numbers such as 199), I can bypass all the validation process. Else, I can show normal HTML validation behaviour with the reportValidity() method.

Here is the code I came up with that I hope does what you want :

var form = document.querySelector("form")       // Get the form
var input = document.querySelector("#myInput")  // Get the input to validate

form.addEventListener("submit", function(e) {
	e.preventDefault()  // Catch the submit
  // Do the magic
  if(onlyStepMatters(input.validity)){
  	form.submit()
  }else {
  	form.reportValidity()
  }
})

function onlyStepMatters(validityState) {
  return !(
    validityState.badInput || validityState.customError || validityState. patternMismatch || validityState.rangeOverflow || validityState.rangeUnderflow || validityState.tooLong || validityState.tooShort || validityState.typeMismatch || validityState.valueMissing
    )
    
  /* This is what the object looks like, notice I just skipped the stepMismatch */
  /*
  {
    badInput,
    customError,
    patternMismatch,
    rangeOverflow,
    rangeUnderflow,
    stepMismatch,
    tooLong,
    tooShort,
    typeMismatch,
    valid,
    valueMissing,
  }
  */
}
<form novalidate>
<input type="number" id="myInput" min="0" max="1000" step = "100" placeholder="Enter a number" required/>
<button type="submit">Send</button> 
</form>

I’m pretty sure this code could be refactored and become more concise based on the same logic, but I don’t have enough time to think more about it.

Any constructive comment will be appreciated.

Hope this helps.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)