I would like to validate a price field in html form that a leading ZERO like 0350, 024879, etc. are not allowed and jQuery will issue a warning while typing. Here is jQuery should do when typing a leading ZERO number into the price field:
a) a popup warning message like ‘ZERO leading number not allowed. Please correct it!’
b) Clear off or remove that invalid price from the price field with/without a delay
c) What is the correct Regex for validating just ZERO leading numeric string? for example, typing 09, 038, etc. is not accepted. But typing 0u, 0& (with non numeric characters) is accepted.
Here is my codes:
HTML:
<input type="text" id="price" name="price">
jQuery:
jQuery('#price').on("keyup", function() {
var price = $(this).val();
var partern = /^(?:[1-9][0-9]*|0)$/;
var valid = partern.test(price);
if (!valid) {
alert('Invalid price. Please input numerical characters');
setTimeout(function (e) {
$this.val(null);
},500);
}
});
Any advice would be very appreciated.
2
Answers
FIXED: Here is my codes:
Many thanks.
ANOTHER FIXED:
I have issue with using both this or (this) in jQuery on my WordPress; they dont work with setTimeout(), and cannot generalise this issue for other Wordpres theme. But I tested this one:
jQuery(‘#price’).val(”); does work with setTimeout() function. Here are full codes with a time delay:
Many thanks