I have some requirement as below:
Example acceptable input: "SAL", "SAL_", "SAL_G"
The problem now:
Code
$('#myInput').on("keypress", function(e) {
var regex = new RegExp("^[A-Z]+(?:_[A-Z]+)*$")
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
} else {
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" type="text" id="myInput" minlength="3" maxlength="8">
Here I have used input
event basically if you used keypress
then it will not works with other touch keyboards.
Also keypress
not supports to copy pasted content also check here.
const inputElements = document.querySelectorAll("#myInput");
inputElements.forEach((inputElement) => {
inputElement.addEventListener("input", function (event) {
let inputText = event.target.value;
let pregExpr = /[^A-Z]/g;
if (inputText.length > 3) {
pregExpr = /[^a-zA-Z]/g;
}
let sanitizedText = inputText.replace(pregExpr, "");
if (sanitizedText.length > 2) {
var trimmedString = sanitizedText.substring(0, 3);
sanitizedText = trimmedString + "_" + sanitizedText.slice(3);
}
event.target.value = sanitizedText;
});
inputElement.addEventListener("keydown", (event) => {
if (event.key === "Backspace") {
let inputText = inputElement.value;
if (inputText.endsWith("_")) {
let newText = inputText.substring(0, inputText.length - 2);
inputElement.value = newText;
} else if (inputText.length > 0) {
let newText = inputText.substring(0, inputText.length - 1);
inputElement.value = newText;
}
event.preventDefault();
}
});
});
<input class="form-control" type="text" id="myInput" minlength="3" maxlength="8">
const inputElements = document.querySelectorAll("#myInput");
inputElements.forEach((inputElement) => {
inputElement.addEventListener("input", function (event) {
const inputText = event.target.value;
let pregExpr = /[^A-Z]/g;
if (inputText.length > 3) {
pregExpr = /[^a-zA-Z]/g;
}
let sanitizedText = inputText.replace(pregExpr, "");
if (sanitizedText.length > 2) {
var trimmedString = sanitizedText.substring(0, 3);
sanitizedText = trimmedString + "_" + sanitizedText.slice(3);
}
event.target.value = sanitizedText;
});
});
<input class="form-control" type="text" id="myInput" minlength="3" maxlength="8">