With javascript I want to limit a contenteditable cell, to allow only numbers and one dot and after the dot max 2 number
valid examples:
in my exaple I
function onlyNumberAndADot(element) {
const invalidChars = /\D/g;
ob = element.target;
if (invalidChars.test(ob.textContent)) {
ob.textContent = ob.textContent.replace(invalidChars, "");
}
}
document.getElementById("test1").addEventListener("input", function(event) {
onlyNumberAndADot(event);
})
#test1 {
border: 1px solid gray;
padding: 5px;
width: 100px;
}
<table class="table">
<tbody>
<tr>
<td id="test1" contenteditable="true"></td>
</tr>
</tbody>
</table>
only in pure javascript I am trying this: [0-9]?(.+)?[0-9]{1,2} but its not okey and I dont know how to implement to my function
not a correct example... because of number 6546545.55
To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers.
If you want to get only digits using REGEXP, use the following regular expression( ^[0-9]*$) in where clause. Case 1 − If you want only those rows which have exactly 10 digits and all must be only digit, use the below regular expression.
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String .
Everytime your event handler runs, the input grows by one character, so I think a better approach would be to check if the input still matches your regex rule and, if not, restore the previous value and force it to blur().
Try to update your event handler like this and it should work:
let curValue = '';
function onlyNumberAndADot(event) {
const valid = /^\d*\.?(?:\d{1,2})?$/;
const text = event.target.textContent;
if (!valid.test(text)) {
event.target.textContent = curValue;
event.target.blur();
} else {
curValue = event.target.textContent;
}
}
document.getElementById("test1").addEventListener("input", function(event) {
onlyNumberAndADot(event);
});
document.getElementById("test1").addEventListener("blur", function(event) {
event.target.textContent = event.target.textContent.replace(/\.$/,'');
});
I created a fiddle with this solution and it works.
Notice that you have to temporarily allow inputs like '0.', otherwise users won't be able to type in the dot, so I did another verification on blur event, to remove the final '.'
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