I am using a document.addEventListener(“DOMContentLoaded”, function ()
to force the input pattern (first must be a letter, then prevent consecutive spaces, etc.)
Now I want to make a 2nd document.addEventListener(“DOMContentLoaded”, function () for an email.
(I want to prevent multiple .’s and prevent more than 1 @)
Here is my code for both of the above but it isn’t working, it only capitalizes the email (i kept that option on to see if that part works, which it does but nothing else does work.)
Here is the first part (I also tried something else, removing the first }); at the document.addEventListener(“DOMContentLoaded”, function () at the start of the 2nd as I heard that should work but that didn’t work either.
document.addEventListener("DOMContentLoaded", function() {
// Function to handle all keypress events
function handleKeyPress(event) {
const input = event.target;
const char = String.fromCharCode(event.which);
// Prevent first character from being a space
if (input.selectionStart === 0 && event.code === "Space") {
event.preventDefault();
return;
}
// Prevent first character from being a non-letter
if (input.selectionStart === 0 && !/^[a-zA-Z]$/.test(char)) {
event.preventDefault();
return;
}
// Prevent consecutive spaces
const lastChar = input.value.charAt(input.selectionStart - 1);
if (char === " " && lastChar === " ") {
event.preventDefault();
return;
}
}
// Attach event listeners to input fields
const inputs = document.querySelectorAll("input[name='real_name'], input[name='display_name']");
inputs.forEach(input => {
input.addEventListener("keypress", handleKeyPress);
// Set text-transform to capitalize to force capitalization of each word
input.style.textTransform = "capitalize";
});
});
document.addEventListener("DOMContentLoaded", function() {
// Function to handle all keypress events
function handleKeyPress2(event) {
const input = event.target;
const char = String.fromCharCode(event.which);
// Prevent first character from being a space
if (input.selectionStart === 0 && event.code === "Space") {
event.preventDefault();
return;
}
// Prevent consecutive spaces
const lastChar = input.value.charAt(input.selectionStart - 1);
if (char === "@" && lastChar === "@") {
event.preventDefault();
return;
}
var key = event.keyCode || event.charCode || event.which;
if (key == 32) {
return false;
} else {
return key;
}
}
// Attach event listeners to input fields
const inputs = document.querySelectorAll("input[name='email']");
inputs.forEach(input => {
input.addEventListener("keydown", handleKeyPress2);
// Set text-transform to capitalize to force capitalization of each word
input.style.textTransform = "capitalize";
});
});