Reputation: 47945
I'm doing a js function that will prevent some input data to be inserted within an input textbox
(only DDDDDD,DD for example):
// decimal
$('.is-decimal').keydown(function (e) {
// prevent to insert non-decimal number (number with comma, max 2 digits after comma)
var elem = $(this);
var value = elem.val();
var regex = /^\d+,?\d{0,2}$/;
if (!regex.test(value)) {
e.preventDefault();
}
});
but I can't use keydown: first time is empty, so it won't check the following char.
Which method should I use? keyup
is later (so it's just inserted); the same with .on("input propertychange", function ()
EDIT: my best attempt:
// decimal
$('.is-decimal').on("input propertychange", function (e) {
var elem = $(this);
var value = elem.val();
// prevent to insert non-decimal number (number with comma, max 2 digits after comma)
var regex = /^\d+,?\d{0,2}$/;
if (!regex.test(value)) {
elem.val(elem.attr('data-actual-value'));
e.preventDefault();
} else {
elem.attr("data-actual-value", value);
}
});
Upvotes: 0
Views: 71
Reputation: 32158
You define a lastValidValue
can use keyup
and change
events to check the newly entered value and if the new value is invalid change it back to the lastValidValue
.
Note: You modify the value without triggering keyup
and keydown
e.g. right-click and paste
Here's an example
let decField = document.querySelector('#decimal')
let lastValidValue = ''
const regex = /^\d+,?\d{0,2}$/;
const eventHandler = e => {
if( event.target.value.match(regex) ) {
lastValidValue = event.target.value
}
else {
event.target.value = lastValidValue
}
}
decField.addEventListener('keyup', eventHandler)
decField.addEventListener('change', eventHandler)
Edit: here's an example with multiple fields using data-regex
attribute to have individual regexes
const eventHandler = e => {
let regex = new RegExp(event.target.dataset.regex);
if( regex.test(event.target.value) ) {
event.target.dataset.lastValidValue = event.target.value
}
else {
event.target.value = event.target.dataset.lastValidValue || ''
}
}
document.querySelectorAll('input[data-regex]').forEach(field => {
field.addEventListener('keyup', eventHandler);
field.addEventListener('change', eventHandler);
})
<input type="text" data-regex="^\d+,?\d{0,2}$" placeholder="digits" />
<input type="text" data-regex="^[\w\s]+$" placeholder="text" />
<input type="text" data-regex="^\W+$" placeholder="special chars" />
Upvotes: 1