Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger html5 validation without form post

I want to achieve something like this without form post, as it will redirect the page. enter image description here

here is my code

<form>
  <input type="number" step="any" min="0" required oninvalid="this.setCustomValidity('Please enter price with decimal format, eg x.xx .')">
  <button type="submit">submit</button>
</form>

I've did some research it seems like it has to be triggered with form post. Possible to trigger the html5 validtion with jquery function button click ?

like image 463
Darren Lau Avatar asked Jun 07 '16 15:06

Darren Lau


1 Answers

Set a custom validation message on input change and intercept the form submit event:

var form = document.querySelector('form'),
    input = document.querySelector('#input-price');

input.addEventListener("change", function (event) {
  if (!input.checkValidity() || !/^\d+(\.\d+)?$/.test(input.value)) {
    input.setCustomValidity("Please enter price with decimal format, eg x.xx .");
  } else {
    input.setCustomValidity("");
  }
});

form.addEventListener("submit", function (event) {
  event.preventDefault();
});
<form>
  <input id="input-price" type="number" step="any" min="0" required>
  <input type="submit">
</form>

input.checkValidity() returns true when the input value is a number as in 2, .1 and 1e10. The regex test then filters the two last cases (.1 and 1e10) out.

like image 167
le_m Avatar answered Sep 18 '22 02:09

le_m