Reputation: 2045
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 ?
Upvotes: 7
Views: 2136
Reputation: 1242
the only way is to use JavaScript code
try this code
Html
<input id="amount" maxlength="7" type="text" />
javaScript
$("#amount").on("keyup", function(){
var valid = /^\d{0,4}(\.\d{0,3})?$/.test(this.value),
val = this.value;
if(!valid){
alert("Please enter price with decimal format, eg x.xx!");
this.value = val.substring(0, val.length - 1);
}
});
try this second solution :
html
<input id="amount" maxlength="7" type="text" />
JS
$("#amount").on("change paste keyup", function(){
var valid = /^\d*(\.\d*)?$/.test(this.value),
val = this.value;
if(!valid){
alert("Please enter price with decimal format, eg x.xx!");
this.value = val.substring(0, val.length - 7);
}
});
result : http://jsfiddle.net/vY39r/866/
Upvotes: 0
Reputation: 20228
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.
Upvotes: 1