The only things I need changed and added to the following code is to only allow 1 @ in the email, and in the names to force only the first letter (of each word) capitalized and the rest of that name forced small, numbers or special characters. I can probably figure it out if you just give me the codes or you could also help me fit it into my current code:
function handleNameFieldKeypress (target, evt) {
console.log('handleNameFieldKeypress ... target ...', target);
const char = String.fromCharCode(evt.which);
const { selectionStart } = target;
const isNotValid = (selectionStart === 0 && (
evt.code === 'Space' || !/^[a-zA-Z]$/.test(char)
)) || (
char === ' ' &&
target.value.charAt(selectionStart - 1) === ' '
);
if (isNotValid) {
evt.preventDefault();
}
}
function handleEmailFieldKeypress (target, evt) {
console.log('handleEmailFieldKeypress ... target ...', target);
const { selectionStart } = target;
const isNotValid =
(selectionStart === 0 && evt.code === 'Space') || (
String.fromCharCode(evt.which) === '@' &&
target.value.charAt(selectionStart - 1) === '@') || (
String.fromCharCode(evt.which) === '@' &&
target.value.charAt(selectionStart - 1) === '.') || (
String.fromCharCode(evt.which) === '.' &&
target.value.charAt(selectionStart - 1) === '@') || (
String.fromCharCode(evt.which) === '.' &&
target.value.charAt(selectionStart - 1) === '.'
);
if (isNotValid) {
evt.preventDefault();
return;
}
const key = evt.keyCode || evt.charCode || evt.which;
return (key !== 32) && key;
}
function handleInputFieldKeypress (evt) {
const { target } = evt;
let result;
if (target.matches('input[name="real_name"], input[name="display_name"]')) {
result = handleNameFieldKeypress(target, evt);
} else if (target.matches('input[name="email"]')) {
result = handleEmailFieldKeypress(target, evt);
}
return result;
}
document
.addEventListener('DOMContentLoaded', () => {
document
.querySelector('form')
.addEventListener('keypress', handleInputFieldKeypress);
});