I want to achieve something like this without form post, as it will redirect the page.
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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With