Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 validation check input bigger than 0

I have an input field which be should bigger than 0, I'm using min="0.00000001" to validate input number is > 0.

<input type="number" step="0.00000001" min="0.00000001" name="price" value="[%price%]" />

Since I don't want to specify the step and min, I just want to validate if the input number is bigger than 0.

Is there any better way to compare input? For example something like input > 0 or min > 0

I search for a solution but could not find one without using step+min.

Using only html5, can we do this? Thanks for any help

<form method="post">
  <b>Number Input:</b>
  <input type="number" step="0.00000001" min="0.00000001" name="number" value="" />
  <input type="submit" class="submit" value="Save" />
</form>
like image 978
Dalin Huang Avatar asked Feb 05 '23 12:02

Dalin Huang


1 Answers

There is no way doing this in pure HTML5 without JavaScript. As mentioned in comments, the pattern attribute cannot be used.

But this can be handled using trivial JavaScript code, invoked via the oninput attribute, and using setCustomValidity:

<form method="post">
  <b>Number Input:</b>
  <input type="number" step="any" min="0"  name="number" value="" 
         oninput="check(this)" />
  <input type="submit" class="submit" value="Save" />
</form>
<script>
 function check(input) {
   if (input.value == 0) {
     input.setCustomValidity('The number must not be zero.');
   } else {
     // input is fine -- reset the error message
     input.setCustomValidity('');
   }
 }
</script>
like image 177
Jukka K. Korpela Avatar answered Feb 07 '23 12:02

Jukka K. Korpela